From 7e9b96e3542e37640849fa4dfb1e40466d2dbe07 Mon Sep 17 00:00:00 2001 From: Aaron Walker Date: Sat, 23 Apr 2016 18:14:31 -0400 Subject: [PATCH] cp/mirror use CopyObject API to enable server side copy (#1686) Add Copy to s3 and fs methods/enable server side copy --- client-fs.go | 81 +++++++++++++++++++++++++++++++++++++++++++++++ client-fs_test.go | 22 +++++++++++++ client-s3.go | 42 ++++++++++++++++++++++++ client.go | 1 + common-methods.go | 13 ++++++++ cp-main.go | 59 ++++++++++++++++++++++++++++------ mirror-main.go | 56 +++++++++++++++++++++++++------- 7 files changed, 252 insertions(+), 22 deletions(-) diff --git a/client-fs.go b/client-fs.go index 7a3efe5c..6b64713c 100644 --- a/client-fs.go +++ b/client-fs.go @@ -261,6 +261,87 @@ func (f *fsClient) ShareUpload(startsWith bool, expires time.Duration, contentTy }) } +// readFile reads and returns the data inside the file located +// at the provided filepath. +func readFile(fpath string) (io.ReadCloser, error) { + // Golang strips trailing / if you clean(..) or + // EvalSymlinks(..). Adding '.' prevents it from doing so. + if strings.HasSuffix(fpath, "/") { + fpath = fpath + "." + } + fpath, e := filepath.EvalSymlinks(fpath) + if e != nil { + return nil, e + } + fileData, e := os.Open(fpath) + if e != nil { + return nil, e + } + return fileData, nil +} + +// createFile creates an empty file at the provided filepath +// if one does not exist already. +func createFile(fpath string) (io.WriteCloser, error) { + st, e := os.Stat(fpath) + // If destination exists but is not regular. + if e == nil && !st.Mode().IsRegular() { + return nil, PathIsNotRegular{Path: fpath} + } + // If file exists already. + if e != nil && !os.IsNotExist(e) { + return nil, e + } + if e = os.MkdirAll(filepath.Dir(fpath), 0775); e != nil { + return nil, e + } + file, e := os.Create(fpath) + if e != nil { + return nil, e + } + return file, nil +} + +// Copy - copy data from source to destination +func (f *fsClient) Copy(source string, size int64, progress io.Reader) *probe.Error { + // Don't use f.Get() f.Put() directly. Instead use readFile and createFile + destination := f.PathURL.Path + if destination == source { // Cannot copy file into itself + return errOverWriteNotAllowed(destination).Trace(destination) + } + rc, e := readFile(source) + if e != nil { + err := f.toClientError(e, destination) + return err.Trace(destination) + } + defer rc.Close() + wc, e := createFile(destination) + if e != nil { + err := f.toClientError(e, destination) + return err.Trace(destination) + } + defer wc.Close() + reader := hookreader.NewHook(rc, progress) + // Perform copy + n, e := io.CopyN(wc, reader, size) // e == nil only if n != size + // Only check size related errors if size is positive + if size > 0 { + if n < size { // Unexpected early EOF + return probe.NewError(UnexpectedEOF{ + TotalSize: size, + TotalWritten: n, + }) + } + if n > size { // Unexpected ExcessRead + return probe.NewError(UnexpectedExcessRead{ + TotalSize: size, + TotalWritten: n, + }) + } + } + return nil +} + // GetPartial download a part object from bucket. // sets err for any errors, reader is nil for errors. func (f *fsClient) Get() (io.Reader, *probe.Error) { diff --git a/client-fs_test.go b/client-fs_test.go index c4a27912..69e25bce 100644 --- a/client-fs_test.go +++ b/client-fs_test.go @@ -320,3 +320,25 @@ func (s *TestSuite) TestStatObject(c *C) { c.Assert(err, IsNil) c.Assert(content.Size, Equals, int64(dataLen)) } + +// Test copy. +func (s *TestSuite) TestCopy(c *C) { + root, e := ioutil.TempDir(os.TempDir(), "fs-") + c.Assert(e, IsNil) + defer os.RemoveAll(root) + sourcePath := filepath.Join(root, "source") + targetPath := filepath.Join(root, "target") + fsClientTarget, err := fsNew(targetPath) + fsClientSource, err := fsNew(sourcePath) + c.Assert(err, IsNil) + + data := "hello world" + var reader io.Reader + reader = bytes.NewReader([]byte(data)) + n, err := fsClientSource.Put(reader, int64(len(data)), "application/octet-stream", nil) + c.Assert(err, IsNil) + c.Assert(n, Equals, int64(len(data))) + + err = fsClientTarget.Copy(sourcePath, int64(len(data)), nil) + c.Assert(err, IsNil) +} diff --git a/client-s3.go b/client-s3.go index 8325a865..305dbd34 100644 --- a/client-s3.go +++ b/client-s3.go @@ -29,6 +29,8 @@ import ( "sync" "time" + "io/ioutil" + "github.com/minio/mc/pkg/httptracer" "github.com/minio/minio-go" "github.com/minio/minio/pkg/probe" @@ -151,6 +153,46 @@ func (c *s3Client) Get() (io.Reader, *probe.Error) { return reader, nil } +// Copy - copy object +func (c *s3Client) Copy(source string, size int64, progress io.Reader) *probe.Error { + bucket, object := c.url2BucketAndObject() + if bucket == "" { + return probe.NewError(BucketNameEmpty{}) + } + // Empty copy conditions + copyConds := minio.NewCopyConditions() + e := c.api.CopyObject(bucket, object, source, copyConds) + if e != nil { + errResponse := minio.ToErrorResponse(e) + if errResponse.Code == "AccessDenied" { + return probe.NewError(PathInsufficientPermission{ + Path: c.targetURL.String(), + }) + } + if errResponse.Code == "NoSuchBucket" { + return probe.NewError(BucketDoesNotExist{ + Bucket: bucket, + }) + } + if errResponse.Code == "InvalidBucketName" { + return probe.NewError(BucketInvalid{ + Bucket: bucket, + }) + } + if errResponse.Code == "NoSuchKey" || errResponse.Code == "InvalidArgument" { + return probe.NewError(ObjectMissing{}) + } + return probe.NewError(e) + } + // Successful copy update progress bar if there is one. + if progress != nil { + if _, e := io.CopyN(ioutil.Discard, progress, size); e != nil { + return probe.NewError(e) + } + } + return nil +} + // Put - put object. func (c *s3Client) Put(reader io.Reader, size int64, contentType string, progress io.Reader) (int64, *probe.Error) { // md5 is purposefully ignored since AmazonS3 does not return proper md5sum diff --git a/client.go b/client.go index ae1d46fd..3c9bcc46 100644 --- a/client.go +++ b/client.go @@ -40,6 +40,7 @@ type Client interface { // I/O operations Get() (reader io.Reader, err *probe.Error) Put(reader io.Reader, size int64, contentType string, progress io.Reader) (n int64, err *probe.Error) + Copy(source string, size int64, progress io.Reader) *probe.Error // I/O operations with expiration ShareDownload(expires time.Duration) (string, *probe.Error) diff --git a/common-methods.go b/common-methods.go index 8d0f8242..792cdc08 100644 --- a/common-methods.go +++ b/common-methods.go @@ -96,6 +96,19 @@ func putTargetStream(urlStr string, reader io.Reader, size int64) (int64, *probe return putTargetStreamFromAlias(alias, urlStrFull, reader, size, nil) } +// copyTargetStreamFromAlias copies to URL from source. +func copySourceStreamFromAlias(alias string, urlStr string, source string, size int64, progress io.Reader) *probe.Error { + targetClnt, err := newClientFromAlias(alias, urlStr) + if err != nil { + return err.Trace(alias, urlStr) + } + err = targetClnt.Copy(source, size, progress) + if err != nil { + return err.Trace(alias, urlStr) + } + return nil +} + // newClientFromAlias gives a new client interface for matching // alias entry in the mc config file. If no matching host config entry // is found, fs client is returned. diff --git a/cp-main.go b/cp-main.go index c137558a..7378ac97 100644 --- a/cp-main.go +++ b/cp-main.go @@ -112,6 +112,11 @@ type copyStatMessage struct { Speed float64 } +const ( + // 5GiB. + fiveGB = 5 * 1024 * 1024 * 1024 +) + // copyStatMessage copy accounting message func (c copyStatMessage) String() string { speedBox := pb.Format(int64(c.Speed)).To(pb.U_BYTES).String() @@ -142,12 +147,6 @@ func doCopy(cpURLs copyURLs, progressReader *progressBar, accountingReader *acco targetURL := cpURLs.TargetContent.URL length := cpURLs.SourceContent.Size - reader, err := getSourceStreamFromAlias(sourceAlias, sourceURL.String()) - if err != nil { - cpURLs.Error = err.Trace(sourceURL.String()) - return cpURLs - } - var progress io.Reader if globalQuiet || globalJSON { sourcePath := filepath.ToSlash(filepath.Join(sourceAlias, sourceURL.Path)) @@ -164,10 +163,50 @@ func doCopy(cpURLs copyURLs, progressReader *progressBar, accountingReader *acco // Set up progress reader. progress = progressReader.ProgressBar } - _, err = putTargetStreamFromAlias(targetAlias, targetURL.String(), reader, length, progress) - if err != nil { - cpURLs.Error = err.Trace(targetURL.String()) - return cpURLs + // If source size is <= 5GB and operation is across same server type try to use Copy. + if length <= fiveGB && (sourceURL.Type == targetURL.Type) { + // FS -> FS Copy includes alias in path. + if sourceURL.Type == fileSystem { + sourcePath := filepath.ToSlash(filepath.Join(sourceAlias, sourceURL.Path)) + err := copySourceStreamFromAlias(targetAlias, targetURL.String(), sourcePath, length, progress) + if err != nil { + cpURLs.Error = err.Trace(sourceURL.String()) + return cpURLs + } + } else if sourceURL.Type == objectStorage { + // If source/target are object storage their aliases must be the same. + if sourceAlias == targetAlias { + // Do not include alias inside path for ObjStore -> ObjStore. + err := copySourceStreamFromAlias(targetAlias, targetURL.String(), sourceURL.Path, length, progress) + if err != nil { + cpURLs.Error = err.Trace(sourceURL.String()) + return cpURLs + } + } else { + reader, err := getSourceStreamFromAlias(sourceAlias, sourceURL.String()) + if err != nil { + cpURLs.Error = err.Trace(sourceURL.String()) + return cpURLs + } + _, err = putTargetStreamFromAlias(targetAlias, targetURL.String(), reader, length, progress) + if err != nil { + cpURLs.Error = err.Trace(targetURL.String()) + return cpURLs + } + } + } + } else { + // Standard GET/PUT for size > 5GB. + reader, err := getSourceStreamFromAlias(sourceAlias, sourceURL.String()) + if err != nil { + cpURLs.Error = err.Trace(sourceURL.String()) + return cpURLs + } + _, err = putTargetStreamFromAlias(targetAlias, targetURL.String(), reader, length, progress) + if err != nil { + cpURLs.Error = err.Trace(targetURL.String()) + return cpURLs + } } cpURLs.Error = nil // just for safety return cpURLs diff --git a/mirror-main.go b/mirror-main.go index ee88cc34..6b382838 100644 --- a/mirror-main.go +++ b/mirror-main.go @@ -196,19 +196,51 @@ func doMirror(sURLs mirrorURLs, progressReader *progressBar, accountingReader *a sURLs.Error = nil return sURLs } - - reader, err := getSourceStreamFromAlias(sourceAlias, sourceURL.String()) - if err != nil { - sURLs.Error = err.Trace(sourceURL.String()) - return sURLs + // If source size is <= 5GB and operation is across same server type try to use Copy. + if length <= fiveGB && sourceURL.Type == targetURL.Type { + // FS -> FS Copy includes alias in path. + if sourceURL.Type == fileSystem { + sourcePath := filepath.ToSlash(filepath.Join(sourceAlias, sourceURL.Path)) + err := copySourceStreamFromAlias(targetAlias, targetURL.String(), sourcePath, length, progress) + if err != nil { + sURLs.Error = err.Trace(sourceURL.String()) + return sURLs + } + } else if sourceURL.Type == objectStorage { + if sourceAlias == targetAlias { + // If source/target are object storage their aliases must be the same + // Do not include alias inside path for ObjStore -> ObjStore. + err := copySourceStreamFromAlias(targetAlias, targetURL.String(), sourceURL.Path, length, progress) + if err != nil { + sURLs.Error = err.Trace(sourceURL.String()) + return sURLs + } + } else { + reader, err := getSourceStreamFromAlias(sourceAlias, sourceURL.String()) + if err != nil { + sURLs.Error = err.Trace(sourceURL.String()) + return sURLs + } + _, err = putTargetStreamFromAlias(targetAlias, targetURL.String(), reader, length, progress) + if err != nil { + sURLs.Error = err.Trace(targetURL.String()) + return sURLs + } + } + } + } else { + // Standard GET/PUT for size > 5GB + reader, err := getSourceStreamFromAlias(sourceAlias, sourceURL.String()) + if err != nil { + sURLs.Error = err.Trace(sourceURL.String()) + return sURLs + } + _, err = putTargetStreamFromAlias(targetAlias, targetURL.String(), reader, length, progress) + if err != nil { + sURLs.Error = err.Trace(targetURL.String()) + return sURLs + } } - - _, err = putTargetStreamFromAlias(targetAlias, targetURL.String(), reader, length, progress) - if err != nil { - sURLs.Error = err.Trace(targetURL.String()) - return sURLs - } - sURLs.Error = nil // just for safety return sURLs }