From 5ddf9728f87e0a0203ab24bdc8d390addfd7175a Mon Sep 17 00:00:00 2001 From: "A. Elleuch" Date: Fri, 8 Dec 2017 01:20:34 +0100 Subject: [PATCH] Parallelize upload/remove in cp/mirror commands (#2289) This PR removes --parallel flag and implements a dynamic way of adding threads to accelerate mirror/cp command. After the calculation of objects that need to be copied/removed, mc sends tasks (upload/remove) to a parallel manager which monitors the progress of tasks and decide to allocate more threads to it to accelerate the overall work. This is very useful when we copy/mirror many relatively small files. --- cmd/accounting-reader.go | 5 ++ cmd/cp-main.go | 110 ++++++++++++----------------- cmd/mirror-main.go | 20 +++++- cmd/parallel-manager.go | 148 +++++++++++++++++++++++++++++++++++++++ cmd/status.go | 6 ++ 5 files changed, 219 insertions(+), 70 deletions(-) create mode 100644 cmd/parallel-manager.go diff --git a/cmd/accounting-reader.go b/cmd/accounting-reader.go index fd433bdd..34894aea 100644 --- a/cmd/accounting-reader.go +++ b/cmd/accounting-reader.go @@ -122,6 +122,11 @@ func (a *accounter) Set(n int64) *accounter { return a } +// Get gets current value atomically +func (a *accounter) Get() int64 { + return atomic.LoadInt64(&a.current) +} + // Add add to current value atomically. func (a *accounter) Add(n int64) int64 { return atomic.AddInt64(&a.current, n) diff --git a/cmd/cp-main.go b/cmd/cp-main.go index 75801cc4..965f8151 100644 --- a/cmd/cp-main.go +++ b/cmd/cp-main.go @@ -25,7 +25,6 @@ import ( "os" "path/filepath" "strings" - "sync" "syscall" "github.com/cheggaaa/pb" @@ -42,11 +41,6 @@ var ( Name: "recursive, r", Usage: "Copy recursively.", }, - cli.UintFlag{ - Name: "parallel, p", - Usage: "Number of copies in parallel", - Value: 1, - }, } ) @@ -74,19 +68,16 @@ EXAMPLES: 2. Copy a folder recursively from Minio cloud storage to Amazon S3 cloud storage. $ {{.HelpName}} --recursive play/mybucket/burningman2011/ s3/mybucket/ - 3. Copy a folder recursively from Minio cloud storage to Amazon S3 cloud storage in parallel. - $ {{.HelpName}} --recursive --parallel 10 play/mybucket/burningman2011/ s3/mybucket/ - - 4. Copy multiple local folders recursively to Minio cloud storage. + 3. Copy multiple local folders recursively to Minio cloud storage. $ {{.HelpName}} --recursive backup/2014/ backup/2015/ play/archive/ - 5. Copy a bucket recursively from aliased Amazon S3 cloud storage to local filesystem on Windows. + 4. Copy a bucket recursively from aliased Amazon S3 cloud storage to local filesystem on Windows. $ {{.HelpName}} --recursive s3\documents\2014\ C:\Backups\2014 - 6. Copy an object with name containing unicode characters to Amazon S3 cloud storage. + 5. Copy an object with name containing unicode characters to Amazon S3 cloud storage. $ {{.HelpName}} 本語 s3/andoria/ - 7. Copy a local folder with space separated characters to Amazon S3 cloud storage. + 6. Copy a local folder with space separated characters to Amazon S3 cloud storage. $ {{.HelpName}} --recursive 'workdir/documents/May 2014/' s3/miniocloud `, @@ -136,25 +127,35 @@ func (c copyStatMessage) String() string { return message } +// Progress - an interface which describes current amount +// of data written. +type Progress interface { + Get() int64 +} + +// ProgressReader can be used to update the progress of +// an on-going transfer progress. +type ProgressReader interface { + io.Reader + Progress +} + // doCopy - Copy a singe file from source to destination -func doCopy(ctx context.Context, cpURLs URLs, progressReader *progressBar, accountingReader *accounter) URLs { +func doCopy(ctx context.Context, cpURLs URLs, pg ProgressReader) URLs { if cpURLs.Error != nil { cpURLs.Error = cpURLs.Error.Trace() return cpURLs } - if !globalQuiet && !globalJSON { - progressReader = progressReader.SetCaption(cpURLs.SourceContent.URL.String() + ": ") - } - sourceAlias := cpURLs.SourceAlias sourceURL := cpURLs.SourceContent.URL targetAlias := cpURLs.TargetAlias targetURL := cpURLs.TargetContent.URL length := cpURLs.SourceContent.Size - var progress io.Reader - if globalQuiet || globalJSON { + if progressReader, ok := pg.(*progressBar); ok { + progressReader.SetCaption(cpURLs.SourceContent.URL.String() + ": ") + } else { sourcePath := filepath.ToSlash(filepath.Join(sourceAlias, sourceURL.Path)) targetPath := filepath.ToSlash(filepath.Join(targetAlias, targetURL.Path)) printMsg(copyMessage{ @@ -164,20 +165,13 @@ func doCopy(ctx context.Context, cpURLs URLs, progressReader *progressBar, accou TotalCount: cpURLs.TotalCount, TotalSize: cpURLs.TotalSize, }) - // Proxy reader to accounting reader only during quiet mode. - if globalQuiet || globalJSON { - progress = accountingReader - } - } else { - // Set up progress reader. - progress = progressReader.ProgressBar } - return uploadSourceToTargetURL(ctx, cpURLs, progress) + return uploadSourceToTargetURL(ctx, cpURLs, pg) } // doCopyFake - Perform a fake copy to update the progress bar appropriately. -func doCopyFake(cpURLs URLs, progressReader *progressBar) URLs { - if !globalQuiet && !globalJSON { +func doCopyFake(cpURLs URLs, pg Progress) URLs { + if progressReader, ok := pg.(*progressBar); ok { progressReader.ProgressBar.Add64(cpURLs.SourceContent.Size) } return cpURLs @@ -262,46 +256,25 @@ func doCopySession(session *sessionV8) error { doPrepareCopyURLs(session, trapCh, cancelCopy) } - // Enable accounting reader by default. - accntReader := newAccounter(session.Header.TotalBytes) - // Prepare URL scanner from session data file. urlScanner := bufio.NewScanner(session.NewDataReader()) // isCopied returns true if an object has been already copied // or not. This is useful when we resume from a session. isCopied := isLastFactory(session.Header.LastCopied) - // Number of parallel - parallel := 1 - if session.Header.CommandIntFlags["parallel"] > 1 { - parallel = session.Header.CommandIntFlags["parallel"] - } - // Queue of doCopy() operation. - var queueCh = make(chan URLs, parallel) - // The number of waiting jobs - var waitGroup = &sync.WaitGroup{} + // Store a progress bar or an accounter + var pg ProgressReader // Enable progress bar reader only during default mode. - var progressReader *progressBar if !globalQuiet && !globalJSON { // set up progress bar - progressReader = newProgressBar(session.Header.TotalBytes) + pg = newProgressBar(session.Header.TotalBytes) + } else { + pg = newAccounter(session.Header.TotalBytes) } - // Wait on status of doCopy() operation. var statusCh = make(chan URLs) - for i := 0; i < parallel; i++ { - go func() { - for { - cpURLs, ok := <-queueCh - if !ok { - return - } - statusCh <- doCopy(ctx, cpURLs, progressReader, accntReader) - waitGroup.Done() - } - }() - } + p, queueCh := newParallelManager(statusCh, pg) go func() { // Loop through all urls. @@ -318,18 +291,22 @@ func doCopySession(session *sessionV8) error { // Verify if previously copied, notify progress bar. if isCopied(cpURLs.SourceContent.URL.String()) { - statusCh <- doCopyFake(cpURLs, progressReader) + queueCh <- func() URLs { + return doCopyFake(cpURLs, pg) + } } else { - waitGroup.Add(1) - queueCh <- cpURLs + queueCh <- func() URLs { + return doCopy(ctx, cpURLs, pg) + } } } - // Waiting to complete jobs - waitGroup.Wait() - // Close - close(queueCh) // URLs feeding finished + close(queueCh) + + // Wait for all tasks to be finished + p.wait() + close(statusCh) }() @@ -377,12 +354,12 @@ loop: } } - if !globalQuiet && !globalJSON { + if progressReader, ok := pg.(*progressBar); ok { if progressReader.ProgressBar.Get() > 0 { progressReader.ProgressBar.Finish() } } else { - if !globalJSON && globalQuiet { + if accntReader, ok := pg.(*accounter); ok { console.Println(console.Colorize("Copy", accntReader.Stat().String())) } } @@ -402,7 +379,6 @@ func mainCopy(ctx *cli.Context) error { session := newSessionV8() session.Header.CommandType = "cp" session.Header.CommandBoolFlags["recursive"] = ctx.Bool("recursive") - session.Header.CommandIntFlags["parallel"] = ctx.Int("parallel") var e error if session.Header.RootPath, e = os.Getwd(); e != nil { diff --git a/cmd/mirror-main.go b/cmd/mirror-main.go index b2a58a66..a6599391 100644 --- a/cmd/mirror-main.go +++ b/cmd/mirror-main.go @@ -144,6 +144,8 @@ type mirrorJob struct { // waitgroup for status goroutine, waits till all status // messages have been written and received wgStatus *sync.WaitGroup + + queueCh chan func() URLs // channel for status messages statusCh chan URLs @@ -435,13 +437,16 @@ func (mj *mirrorJob) startMirror(ctx context.Context, cancelMirror context.Cance var totalBytes int64 var totalObjects int64 + parallel, queueCh := newParallelManager(mj.statusCh, mj.status) + URLsCh := prepareMirrorURLs(mj.sourceURL, mj.targetURL, mj.isFake, mj.isOverwrite, mj.isRemove, mj.excludeOptions) + for { select { case sURLs, ok := <-URLsCh: if !ok { // finished harvesting urls - return + goto exit } if sURLs.Error != nil { if strings.Contains(sURLs.Error.ToGoError().Error(), " is a folder.") { @@ -467,15 +472,23 @@ func (mj *mirrorJob) startMirror(ctx context.Context, cancelMirror context.Cance sURLs.TotalSize = mj.TotalBytes if sURLs.SourceContent != nil { - mj.statusCh <- mj.doMirror(ctx, cancelMirror, sURLs) + queueCh <- func() URLs { + return mj.doMirror(ctx, cancelMirror, sURLs) + } } else if sURLs.TargetContent != nil && mj.isRemove { - mj.statusCh <- mj.doRemove(sURLs) + queueCh <- func() URLs { + return mj.doRemove(sURLs) + } } case <-mj.trapCh: cancelMirror() os.Exit(0) } } + +exit: + close(queueCh) + parallel.wait() } // when using a struct for copying, we could save a lot of passing of variables @@ -531,6 +544,7 @@ func newMirrorJob(srcURL, dstURL string, isFake, isRemove, isOverwrite, isWatch status: status, scanBar: func(s string) {}, statusCh: make(chan URLs), + queueCh: make(chan func() URLs), wgStatus: new(sync.WaitGroup), watcherRunning: true, watcher: NewWatcher(UTCNow()), diff --git a/cmd/parallel-manager.go b/cmd/parallel-manager.go new file mode 100644 index 00000000..4cf62272 --- /dev/null +++ b/cmd/parallel-manager.go @@ -0,0 +1,148 @@ +/* + * Minio Client (C) 2017 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 cmd + +import ( + "sync" + "sync/atomic" + "time" +) + +const ( + // Maximum number of parallel workers + maxParallelWorkers = 10 + // Monitor tick to decide to add new workers + monitorPeriod = 5 * time.Second + // jump + jump = 1.20 +) + +// ParallelManager - helps manage parallel workers to run tasks +type ParallelManager struct { + // pb shows current progress + pb Progress + + // Synchronize workers + wg *sync.WaitGroup + + // Total send bytes and current bandwidth + sentBytes int64 + sentBytesPrev int64 + bandwidth float64 + bandwidthPrev float64 + + // Current threads number + threadsNum uint64 + + // Channel to receive tasks to run + queueCh chan func() URLs + // Channel to send back results + resultCh chan URLs + + stopMonitorCh chan struct{} +} + +// addWorker creates a new worker to process tasks +func (p *ParallelManager) addWorker() { + + if atomic.LoadUint64(&p.threadsNum) >= maxParallelWorkers { + // Number of maximum workers is reached, no need to + // to create a new one. + return + } + + // Update number of threads + atomic.AddUint64(&p.threadsNum, 1) + + // Start a new worker + p.wg.Add(1) + go func() { + for { + // Wait for jobs + fn := <-p.queueCh + if fn == nil { + // No more tasks, quit + p.wg.Done() + return + } + // Execute the task and send the result + // to result channel. + p.resultCh <- fn() + } + }() +} + +// monitorProgress monitors realtime transfer speed of data +// and increases threads until it reaches a maximum number of +// threads or notice there is no apparent enhancement of +// transfer speed. +func (p *ParallelManager) monitorProgress() { + if p.pb == nil { + // Nothing to monitor + return + } + go func() { + ticker := time.NewTicker(monitorPeriod) + defer ticker.Stop() + for { + select { + case <-p.stopMonitorCh: + // Ordered to quit immediately + return + case <-ticker.C: + // Get current monitor values + p.sentBytes = p.pb.Get() + p.bandwidth = float64(p.sentBytes - p.sentBytesPrev) + + // Decide if we should add a new worker + if p.bandwidth > jump*p.bandwidthPrev { + p.addWorker() + } + + // Save monitor values + p.sentBytesPrev = p.sentBytes + p.bandwidthPrev = p.bandwidth + } + } + }() +} + +// Wait for all workers to finish tasks before shutting down Parallel +func (p *ParallelManager) wait() { + p.wg.Wait() + close(p.stopMonitorCh) +} + +// newParallelManager starts new workers waiting for executing copy/remove tasks +func newParallelManager(resultCh chan URLs, pb Progress) (*ParallelManager, chan func() URLs) { + p := &ParallelManager{ + pb: pb, + wg: &sync.WaitGroup{}, + threadsNum: 0, + stopMonitorCh: make(chan struct{}), + queueCh: make(chan func() URLs), + resultCh: resultCh, + } + + // Add at least one worker to execute the job + p.addWorker() + + // Start monitoring tasks progress + p.monitorProgress() + + return p, p.queueCh +} diff --git a/cmd/status.go b/cmd/status.go index d037dc02..b1d85943 100644 --- a/cmd/status.go +++ b/cmd/status.go @@ -25,6 +25,7 @@ import ( type Status interface { Println(data ...interface{}) Add(int64) Status + Get() int64 Start() Finish() @@ -61,6 +62,11 @@ func (ds *DummyStatus) Read(p []byte) (n int, err error) { return len(p), nil } +// Get implements Progress interface +func (ds *DummyStatus) Get() int64 { + return 0 +} + // SetTotal sets the total of the progressbar, ignored for quietstatus func (ds *DummyStatus) SetTotal(v int64) Status { return ds