From 9219e1a320bed29e4ce3070ae015e4308089a9eb Mon Sep 17 00:00:00 2001 From: Harshavardhana Date: Sun, 29 Nov 2015 14:43:11 -0800 Subject: [PATCH] mirror/pipe: Enable mirror and pipe back now they do not work for multiple targets. --- Makefile | 2 +- common-methods.go | 76 ----------------------------- main.go | 14 +++--- mirror-main.go | 60 +++++++++++------------ mirror-url.go | 118 ++++++++++++++++++++-------------------------- pipe-main.go | 20 ++++---- 6 files changed, 95 insertions(+), 195 deletions(-) diff --git a/Makefile b/Makefile index 1fba33b2..00d6b103 100644 --- a/Makefile +++ b/Makefile @@ -43,7 +43,7 @@ cyclo: deadcode: @echo "Running $@:" - #@GO15VENDOREXPERIMENT=1 deadcode + @GO15VENDOREXPERIMENT=1 deadcode build: verifiers @echo "Installing mc:" diff --git a/common-methods.go b/common-methods.go index dbd73ee9..d25cf987 100644 --- a/common-methods.go +++ b/common-methods.go @@ -69,82 +69,6 @@ func putTarget(targetURL string, reader io.ReadSeeker, size int64) *probe.Error return nil } -/* -// putTargets writes to URL from reader. If length=-1, read until EOF. -func putTargets(targetURLs []string, length int64, reader io.Reader) *probe.Error { - var tgtReaders []*io.PipeReader - var tgtWriters []*io.PipeWriter - var tgtClients []client.Client - errCh := make(chan *probe.Error) - defer close(errCh) - - for _, targetURL := range targetURLs { - tgtClient, err := url2Client(targetURL) - if err != nil { - return err.Trace(targetURL) - } - tgtClients = append(tgtClients, tgtClient) - tgtReader, tgtWriter := io.Pipe() - tgtReaders = append(tgtReaders, tgtReader) - tgtWriters = append(tgtWriters, tgtWriter) - } - - go func() { - var writers []io.Writer - for _, tgtWriter := range tgtWriters { - writers = append(writers, io.Writer(tgtWriter)) - } - - multiTgtWriter := io.MultiWriter(writers...) - var e error - switch length { - case -1: - _, e = io.Copy(multiTgtWriter, reader) - default: - _, e = io.CopyN(multiTgtWriter, reader, length) - } - for _, tgtWriter := range tgtWriters { - if e != nil { - tgtWriter.CloseWithError(e) - } - tgtWriter.Close() - } - }() - - var wg sync.WaitGroup - errorCh := make(chan *probe.Error, len(tgtClients)) - - func() { // Parallel putObject - defer close(errorCh) // Each routine gets to return one err status. - for i := range tgtClients { - wg.Add(1) - // make local copy for go routine - tgtClient := tgtClients[i] - tgtReader := tgtReaders[i] - - go func(targetClient client.Client, reader io.ReadCloser, errorCh chan<- *probe.Error) { - defer wg.Done() - defer reader.Close() - err := targetClient.Put(length, reader) - if err != nil { - errorCh <- err.Trace(targetClient.GetURL().String()) - return - } - }(tgtClient, tgtReader, errorCh) - } - wg.Wait() - }() - - // Return on first error encounter. - err := <-errorCh - if err != nil { - return err.Trace() - } - - return nil // success. -} -*/ - // getNewClient gives a new client interface func getNewClient(urlStr string, auth hostConfig) (client.Client, *probe.Error) { url := client.NewURL(urlStr) diff --git a/main.go b/main.go index 5bb2ef9c..216b498f 100644 --- a/main.go +++ b/main.go @@ -146,13 +146,13 @@ func findClosestCommands(command string) []string { func registerApp() *cli.App { // Register all the commands (refer flags.go) - registerCmd(lsCmd) // List contents of a bucket. - registerCmd(mbCmd) // Make a bucket. - registerCmd(catCmd) // Display contents of a file. - // registerCmd(pipeCmd) // Write contents of stdin to a file. - registerCmd(shareCmd) // Share documents via URL. - registerCmd(cpCmd) // Copy objects and files from multiple sources to single destination. - // registerCmd(mirrorCmd) // Mirror objects and files from single source to multiple destinations. + registerCmd(lsCmd) // List contents of a bucket. + registerCmd(mbCmd) // Make a bucket. + registerCmd(catCmd) // Display contents of a file. + registerCmd(pipeCmd) // Write contents of stdin to a file. + registerCmd(shareCmd) // Share documents via URL. + registerCmd(cpCmd) // Copy objects and files from multiple sources to single destination. + registerCmd(mirrorCmd) // Mirror objects and files from single source to multiple destinations. registerCmd(diffCmd) // Computer differences between two files or folders. registerCmd(rmCmd) // Remove a file or bucket registerCmd(accessCmd) // Set access permissions. diff --git a/mirror-main.go b/mirror-main.go index f5fd5f90..c9aefc39 100644 --- a/mirror-main.go +++ b/mirror-main.go @@ -1,5 +1,3 @@ -package main - /* * Minio Client, (C) 2015 Minio, Inc. * @@ -14,7 +12,7 @@ package main * 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 @@ -54,14 +52,14 @@ var ( // Mirror folders recursively from a single source to many destinations var mirrorCmd = cli.Command{ Name: "mirror", - Usage: "Mirror folders recursively from a single source to many destinations.", + Usage: "Mirror folders recursively from a single source to single destination.", Action: mainMirror, Flags: append(mirrorFlags, globalFlags...), CustomHelpTemplate: `NAME: mc {{.Name}} - {{.Usage}} USAGE: - mc {{.Name}} [FLAGS] SOURCE TARGET [TARGET...] + mc {{.Name}} [FLAGS] SOURCE TARGET FLAGS: {{range .Flags}}{{.}} @@ -70,24 +68,24 @@ EXAMPLES: 1. Mirror a bucket recursively from Minio cloud storage to a bucket on Amazon S3 cloud storage. $ mc {{.Name}} play.minio.io:9000/photos/2014 s3.amazonaws.com/backup-photos - 2. Mirror a local folder recursively to Minio cloud storage, Amazon S3 cloud storage and Google Cloud Storage. - $ mc {{.Name}} backup/ play.minio.io:9000/archive s3.amazonaws.com/archive storage.googleapis.com/miniocloud + 2. Mirror a local folder recursively to Amazon S3 cloud storage. + $ mc {{.Name}} backup/ s3.amazonaws.com/archive - 3. Mirror a bucket from aliased Amazon S3 cloud storage to multiple folders on Windows. - $ mc {{.Name}} s3/documents/2014/ C:\backup\2014 C:\shared\volume\backup\2014 + 3. Mirror a bucket from aliased Amazon S3 cloud storage to a folder on Windows. + $ mc {{.Name}} s3/documents/2014/ C:\backup\2014 `, } // mirrorMessage container for file mirror messages type mirrorMessage struct { - Status string `json:"status"` - Source string `json:"source"` - Targets []string `json:"targets"` + Status string `json:"status"` + Source string `json:"source"` + Target string `json:"target"` } // String colorized mirror message func (m mirrorMessage) String() string { - return console.Colorize("Mirror", fmt.Sprintf("‘%s’ -> ‘%s’", m.Source, m.Targets)) + return console.Colorize("Mirror", fmt.Sprintf("‘%s’ -> ‘%s’", m.Source, m.Target)) } // JSON jsonified mirror message @@ -132,30 +130,29 @@ func doMirror(sURLs mirrorURLs, progressReader *barSend, accountingReader *accou return } + targetURL := sURLs.TargetContent.URL.String() + sourceURL := sURLs.SourceContent.URL.String() + length := sURLs.SourceContent.Size + if !globalQuiet && !globalJSON { - progressReader.SetCaption(sURLs.SourceContent.URL.String() + ": ") + progressReader.SetCaption(sourceURL + ": ") } - reader, err := getSource(sURLs.SourceContent.URL.String()) + reader, err := getSource(sourceURL) if err != nil { if !globalQuiet && !globalJSON { - progressReader.ErrorGet(int64(sURLs.SourceContent.Size)) + progressReader.ErrorGet(length) } - sURLs.Error = err.Trace(sURLs.SourceContent.URL.String()) + sURLs.Error = err.Trace(sourceURL) statusCh <- sURLs return } - var targetURLs []string - for _, targetContent := range sURLs.TargetContents { - targetURLs = append(targetURLs, targetContent.URL.String()) - } - - var newReader io.ReadCloser + var newReader io.ReadSeeker if globalQuiet || globalJSON { printMsg(mirrorMessage{ - Source: sURLs.SourceContent.URL.String(), - Targets: targetURLs, + Source: sourceURL, + Target: targetURL, }) if globalJSON { newReader = reader @@ -167,14 +164,12 @@ func doMirror(sURLs mirrorURLs, progressReader *barSend, accountingReader *accou // set up progress newReader = progressReader.NewProxyReader(reader) } - defer newReader.Close() - - err = putTargets(targetURLs, length, newReader) + err = putTarget(targetURL, newReader, length) if err != nil { if !globalQuiet && !globalJSON { - progressReader.ErrorPut(int64(length)) + progressReader.ErrorPut(length) } - sURLs.Error = err.Trace(targetURLs...) + sURLs.Error = err.Trace(targetURL) statusCh <- sURLs return } @@ -193,7 +188,7 @@ func doMirrorFake(sURLs mirrorURLs, progressReader *barSend) { // doPrepareMirrorURLs scans the source URL and prepares a list of objects for mirroring. func doPrepareMirrorURLs(session *sessionV5, isForce bool, trapCh <-chan bool) { sourceURL := session.Header.CommandArgs[0] // first one is source. - targetURLs := session.Header.CommandArgs[1:] + targetURL := session.Header.CommandArgs[1] var totalBytes int64 var totalObjects int @@ -205,7 +200,7 @@ func doPrepareMirrorURLs(session *sessionV5, isForce bool, trapCh <-chan bool) { scanBar = scanBarFactory() } - URLsCh := prepareMirrorURLs(sourceURL, targetURLs, isForce) + URLsCh := prepareMirrorURLs(sourceURL, targetURL, isForce) done := false for done == false { select { @@ -401,4 +396,3 @@ func mainMirror(ctx *cli.Context) { doMirrorSession(session) session.Delete() } -*/ diff --git a/mirror-url.go b/mirror-url.go index ec9d2125..9670cdea 100644 --- a/mirror-url.go +++ b/mirror-url.go @@ -26,16 +26,16 @@ import ( ) type mirrorURLs struct { - SourceContent *client.Content - TargetContents []*client.Content - Error *probe.Error `json:"-"` + SourceContent *client.Content + TargetContent *client.Content + Error *probe.Error `json:"-"` } func (m mirrorURLs) isEmpty() bool { - if m.SourceContent == nil && len(m.TargetContents) == 0 && m.Error == nil { + if m.SourceContent == nil && m.TargetContent == nil && m.Error == nil { return true } - if m.SourceContent.Size == 0 && len(m.TargetContents) == 0 && m.Error == nil { + if m.SourceContent.Size == 0 && m.TargetContent == nil && m.Error == nil { return true } return false @@ -44,7 +44,7 @@ func (m mirrorURLs) isEmpty() bool { // // * MIRROR ARGS - VALID CASES // ========================= -// mirror(d1..., [](d2)) -> []mirror(d1/f, [](d2/d1/f)) +// mirror(d1..., d2) -> []mirror(d1/f, d2/d1/f) // checkMirrorSyntax(URLs []string) func checkMirrorSyntax(ctx *cli.Context) { @@ -57,7 +57,7 @@ func checkMirrorSyntax(ctx *cli.Context) { fatalIf(err.Trace(ctx.Args()...), "Unable to parse arguments.") srcURL := URLs[0] - tgtURLs := URLs[1:] + tgtURL := URLs[1] /****** Generic rules *******/ _, srcContent, err := url2Stat(srcURL) @@ -69,27 +69,25 @@ func checkMirrorSyntax(ctx *cli.Context) { fatalIf(errInvalidArgument().Trace(srcContent.URL.String(), srcContent.Type.String()), fmt.Sprintf("Source ‘%s’ is not a folder. Only folders are supported by mirror command.", srcURL)) } - if len(tgtURLs) == 0 && tgtURLs == nil { + if len(tgtURL) == 0 && tgtURL == "" { fatalIf(errInvalidArgument().Trace(), "Invalid target arguments to mirror command.") } - for _, tgtURL := range tgtURLs { - url := client.NewURL(tgtURL) - if url.Host != "" { - if url.Path == string(url.Separator) { - fatalIf(errInvalidArgument().Trace(tgtURL), - fmt.Sprintf("Target ‘%s’ does not contain bucket name.", tgtURL)) - } - } - _, _, err = url2Stat(tgtURL) - // we die on any error other than client.PathNotFound - destination directory need not exist. - if _, ok := err.ToGoError().(client.PathNotFound); !ok { - fatalIf(err.Trace(tgtURL), fmt.Sprintf("Unable to stat %s", tgtURL)) + url := client.NewURL(tgtURL) + if url.Host != "" { + if url.Path == string(url.Separator) { + fatalIf(errInvalidArgument().Trace(tgtURL), + fmt.Sprintf("Target ‘%s’ does not contain bucket name.", tgtURL)) } } + _, _, err = url2Stat(tgtURL) + // we die on any error other than client.PathNotFound - destination directory need not exist. + if _, ok := err.ToGoError().(client.PathNotFound); !ok { + fatalIf(err.Trace(tgtURL), fmt.Sprintf("Unable to stat %s", tgtURL)) + } } -func deltaSourceTargets(sourceURL string, targetURLs []string, isForce bool, mirrorURLsCh chan<- mirrorURLs) { +func deltaSourceTargets(sourceURL string, targetURL string, isForce bool, mirrorURLsCh chan<- mirrorURLs) { defer close(mirrorURLsCh) // source and targets are always directories @@ -97,23 +95,15 @@ func deltaSourceTargets(sourceURL string, targetURLs []string, isForce bool, mir if !strings.HasSuffix(sourceURL, sourceSeparator) { sourceURL = sourceURL + sourceSeparator } - for i, url := range targetURLs { - targetSeparator := string(client.NewURL(url).Separator) - if !strings.HasSuffix(url, targetSeparator) { - targetURLs[i] = url + targetSeparator - } + targetSeparator := string(client.NewURL(targetURL).Separator) + if !strings.HasSuffix(targetURL, targetSeparator) { + targetURL = targetURL + targetSeparator } - // 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]) - if err != nil { - mirrorURLsCh <- mirrorURLs{Error: err.Trace(targetURLs...)} - return - } + objectDifferenceTarget, err := objectDifferenceFactory(targetURL) + if err != nil { + mirrorURLsCh <- mirrorURLs{Error: err.Trace(targetURL)} + return } sourceClient, err := url2Client(sourceURL) @@ -131,42 +121,36 @@ func deltaSourceTargets(sourceURL string, targetURLs []string, isForce bool, mir continue } suffix := strings.TrimPrefix(sourceContent.URL.String(), sourceURL) - targetContents := []*client.Content{} - for i, difference := range objectDifferenceArray { - differ, err := difference(suffix, sourceContent.Type, sourceContent.Size) - if err != nil { - mirrorURLsCh <- mirrorURLs{Error: err.Trace(sourceContent.URL.String())} - continue - } - if differ == differNone { - // no difference, continue - continue - } - if differ == differType { - mirrorURLsCh <- mirrorURLs{Error: errInvalidTarget(suffix)} - continue - } - if differ == differSize && !isForce { - // size differs and force not set - mirrorURLsCh <- mirrorURLs{Error: errOverWriteNotAllowed(sourceContent.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) + differ, err := objectDifferenceTarget(suffix, sourceContent.Type, sourceContent.Size) + if err != nil { + mirrorURLsCh <- mirrorURLs{Error: err.Trace(sourceContent.URL.String())} + continue } - if len(targetContents) > 0 { - mirrorURLsCh <- mirrorURLs{ - SourceContent: sourceContent, - TargetContents: targetContents, - } + if differ == differNone { + // no difference, continue + continue + } + if differ == differType { + mirrorURLsCh <- mirrorURLs{Error: errInvalidTarget(suffix)} + continue + } + if differ == differSize && !isForce { + // size differs and force not set + mirrorURLsCh <- mirrorURLs{Error: errOverWriteNotAllowed(sourceContent.URL.String())} + continue + } + // either available only in source or size differs and force is set + targetPath := urlJoinPath(targetURL, suffix) + targetContent := &client.Content{URL: *client.NewURL(targetPath)} + mirrorURLsCh <- mirrorURLs{ + SourceContent: sourceContent, + TargetContent: targetContent, } } } -func prepareMirrorURLs(sourceURL string, targetURLs []string, isForce bool) <-chan mirrorURLs { +func prepareMirrorURLs(sourceURL string, targetURL string, isForce bool) <-chan mirrorURLs { mirrorURLsCh := make(chan mirrorURLs) - go deltaSourceTargets(sourceURL, targetURLs, isForce, mirrorURLsCh) + go deltaSourceTargets(sourceURL, targetURL, isForce, mirrorURLsCh) return mirrorURLsCh } diff --git a/pipe-main.go b/pipe-main.go index ea2dabf2..501301cd 100644 --- a/pipe-main.go +++ b/pipe-main.go @@ -1,5 +1,3 @@ -package main - /* * Minio Client, (C) 2015 Minio, Inc. * @@ -14,6 +12,7 @@ package main * 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 @@ -37,14 +36,14 @@ var ( // Display contents of a file. var pipeCmd = cli.Command{ Name: "pipe", - Usage: "Write contents of stdin to one or more targets. When no target is specified, it writes to stdout.", + Usage: "Write contents of stdin to one target. When no target is specified, it writes to stdout.", Action: mainPipe, Flags: append(pipeFlags, globalFlags...), CustomHelpTemplate: `NAME: mc {{.Name}} - {{.Usage}} USAGE: - mc {{.Name}} [FLAGS] [TARGET...] + mc {{.Name}} [FLAGS] TARGET FLAGS: {{range .Flags}}{{.}} @@ -57,7 +56,7 @@ EXAMPLES: $ mc {{.Name}} s3.amazonaws.com/personalbuck/meeting-notes.txt 3. Copy an ISO image to an object on Amazon S3 cloud storage and Google Cloud Storage simultaneously. - $ cat debian-8.2.iso | mc {{.Name}} s3.amazonaws.com/ferenginar/gnuos.iso storage.googleapis.com/miniocloud/gnuos.iso + $ cat debian-8.2.iso | mc {{.Name}} s3.amazonaws.com/ferenginar/gnuos.iso 4. Stream MySQL database dump to Amazon S3 directly. $ mysqldump -u root -p ******* accountsdb | mc {{.Name}} s3.amazonaws.com/ferenginar/backups/accountsdb-oct-9-2015.sql @@ -65,8 +64,8 @@ EXAMPLES: } // pipe writes contents of stdin a collection of URLs. -func pipe(targetURLs []string) *probe.Error { - if len(targetURLs) == 0 || targetURLs == nil { +func pipe(targetURL string) *probe.Error { + if len(targetURL) == 0 || targetURL == "" { // When no target is specified, pipe cat's stdin to stdout. return catOut(os.Stdin).Trace() } @@ -74,7 +73,7 @@ func pipe(targetURLs []string) *probe.Error { // Stream from stdin to multiple objects until EOF. // Ignore size, since os.Stat() would not return proper size all the time // for local filesystem for example /proc files. - err := putTargets(targetURLs, -1, os.Stdin) + err := putTarget(targetURL, os.Stdin, -1) // TODO: See if this check is necessary. switch e := err.ToGoError().(type) { case *os.PathError: @@ -83,7 +82,7 @@ func pipe(targetURLs []string) *probe.Error { return nil } } - return err.Trace(targetURLs...) + return err.Trace(targetURL) } // mainPipe is the main entry point for pipe command. @@ -95,7 +94,6 @@ func mainPipe(ctx *cli.Context) { URLs, err := args2URLs(ctx.Args()) fatalIf(err.Trace(ctx.Args()...), "Unable to parse arguments.") - err = pipe(URLs) + err = pipe(URLs[0]) fatalIf(err.Trace(URLs...), "Unable to write to one or more targets.") } -*/