Add metadata in mc copy (#2671)
Example : mc cp --attr key1=value1,key2=value2 play/mybucket/burningman2011/ ~/latest/
This commit is contained in:
committed by
Nitish Tiwari
parent
4a130c60a8
commit
2e612b23d6
+1
-1
@@ -367,7 +367,7 @@ func readFile(fpath string) (io.ReadCloser, error) {
|
||||
}
|
||||
|
||||
// Copy - copy data from source to destination
|
||||
func (f *fsClient) Copy(source string, size int64, progress io.Reader, srcSSE, tgtSSE encrypt.ServerSide) *probe.Error {
|
||||
func (f *fsClient) Copy(source string, size int64, progress io.Reader, srcSSE, tgtSSE encrypt.ServerSide, metadata map[string]string) *probe.Error {
|
||||
destination := f.PathURL.Path
|
||||
rc, e := readFile(source)
|
||||
if e != nil {
|
||||
|
||||
@@ -360,6 +360,6 @@ func (s *TestSuite) TestCopy(c *C) {
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(n, Equals, int64(len(data)))
|
||||
|
||||
err = fsClientTarget.Copy(sourcePath, int64(len(data)), nil, nil, nil)
|
||||
err = fsClientTarget.Copy(sourcePath, int64(len(data)), nil, nil, nil, nil)
|
||||
c.Assert(err, IsNil)
|
||||
}
|
||||
|
||||
+2
-2
@@ -626,7 +626,7 @@ func (c *s3Client) Get(sse encrypt.ServerSide) (io.ReadCloser, *probe.Error) {
|
||||
// Copy - copy object, uses server side copy API. Also uses an abstracted API
|
||||
// such that large file sizes will be copied in multipart manner on server
|
||||
// side.
|
||||
func (c *s3Client) Copy(source string, size int64, progress io.Reader, srcSSE, tgtSSE encrypt.ServerSide) *probe.Error {
|
||||
func (c *s3Client) Copy(source string, size int64, progress io.Reader, srcSSE, tgtSSE encrypt.ServerSide, metadata map[string]string) *probe.Error {
|
||||
dstBucket, dstObject := c.url2BucketAndObject()
|
||||
if dstBucket == "" {
|
||||
return probe.NewError(BucketNameEmpty{})
|
||||
@@ -638,7 +638,7 @@ func (c *s3Client) Copy(source string, size int64, progress io.Reader, srcSSE, t
|
||||
src := minio.NewSourceInfo(tokens[1], tokens[2], srcSSE)
|
||||
|
||||
// Destination object
|
||||
dst, e := minio.NewDestinationInfo(dstBucket, dstObject, tgtSSE, nil)
|
||||
dst, e := minio.NewDestinationInfo(dstBucket, dstObject, tgtSSE, metadata)
|
||||
if e != nil {
|
||||
return probe.NewError(e)
|
||||
}
|
||||
|
||||
+2
-1
@@ -57,7 +57,7 @@ type Client interface {
|
||||
SetAccess(access string, isJSON bool) *probe.Error
|
||||
|
||||
// I/O operations
|
||||
Copy(source string, size int64, progress io.Reader, srcSSE, tgtSSE encrypt.ServerSide) *probe.Error
|
||||
Copy(source string, size int64, progress io.Reader, srcSSE, tgtSSE encrypt.ServerSide, metadata map[string]string) *probe.Error
|
||||
|
||||
// Runs select expression on object storage on specific files.
|
||||
Select(expression string, sse encrypt.ServerSide) (io.ReadCloser, *probe.Error)
|
||||
@@ -87,6 +87,7 @@ type clientContent struct {
|
||||
Size int64
|
||||
Type os.FileMode
|
||||
Metadata map[string]string
|
||||
UserMetadata map[string]string
|
||||
ETag string
|
||||
Expires time.Time
|
||||
EncryptionHeaders map[string]string
|
||||
|
||||
+40
-3
@@ -194,18 +194,43 @@ func putTargetStreamWithURL(urlStr string, reader io.Reader, size int64, sse enc
|
||||
}
|
||||
|
||||
// copySourceToTargetURL copies to targetURL from source.
|
||||
func copySourceToTargetURL(alias string, urlStr string, source string, size int64, progress io.Reader, srcSSE, tgtSSE encrypt.ServerSide) *probe.Error {
|
||||
func copySourceToTargetURL(alias string, urlStr string, source string, size int64, progress io.Reader, srcSSE, tgtSSE encrypt.ServerSide, metadata map[string]string) *probe.Error {
|
||||
targetClnt, err := newClientFromAlias(alias, urlStr)
|
||||
if err != nil {
|
||||
return err.Trace(alias, urlStr)
|
||||
}
|
||||
err = targetClnt.Copy(source, size, progress, srcSSE, tgtSSE)
|
||||
err = targetClnt.Copy(source, size, progress, srcSSE, tgtSSE, metadata)
|
||||
if err != nil {
|
||||
return err.Trace(alias, urlStr)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// createUserMetadata - returns a map of user defined function
|
||||
// by combining the usermetadata of object and values passed by attr keyword
|
||||
func createUserMetadata(sourceAlias, sourceURLStr string, srcSSE encrypt.ServerSide, urls URLs) (map[string]string, *probe.Error) {
|
||||
metadata := make(map[string]string)
|
||||
sourceClnt, err := newClientFromAlias(sourceAlias, sourceURLStr)
|
||||
if err != nil {
|
||||
return nil, err.Trace(sourceAlias, sourceURLStr)
|
||||
}
|
||||
st, err := sourceClnt.Stat(false, true, srcSSE)
|
||||
if err != nil {
|
||||
return nil, err.Trace(sourceAlias, sourceURLStr)
|
||||
}
|
||||
for k, v := range st.Metadata {
|
||||
if httpguts.ValidHeaderFieldName(k) && strings.HasPrefix(k, "X-Amz-Meta-") &&
|
||||
httpguts.ValidHeaderFieldValue(v) {
|
||||
metadata[k] = v
|
||||
}
|
||||
}
|
||||
|
||||
for k, v := range urls.TargetContent.UserMetadata {
|
||||
metadata[k] = v
|
||||
}
|
||||
return metadata, nil
|
||||
}
|
||||
|
||||
// uploadSourceToTargetURL - uploads to targetURL from source.
|
||||
// optionally optimizes copy for object sizes <= 5GiB by using
|
||||
// server side copy operation.
|
||||
@@ -224,8 +249,14 @@ func uploadSourceToTargetURL(ctx context.Context, urls URLs, progress io.Reader,
|
||||
|
||||
// Optimize for server side copy if the host is same.
|
||||
if sourceAlias == targetAlias {
|
||||
|
||||
metadata, err := createUserMetadata(sourceAlias, sourceURL.String(), srcSSE, urls)
|
||||
if err != nil {
|
||||
return urls.WithError(err.Trace(sourceURL.String()))
|
||||
}
|
||||
|
||||
sourcePath := filepath.ToSlash(sourceURL.Path)
|
||||
err := copySourceToTargetURL(targetAlias, targetURL.String(), sourcePath, length, progress, srcSSE, tgtSSE)
|
||||
err = copySourceToTargetURL(targetAlias, targetURL.String(), sourcePath, length, progress, srcSSE, tgtSSE, metadata)
|
||||
if err != nil {
|
||||
return urls.WithError(err.Trace(sourceURL.String()))
|
||||
}
|
||||
@@ -243,6 +274,12 @@ func uploadSourceToTargetURL(ctx context.Context, urls URLs, progress io.Reader,
|
||||
metadata[k] = v
|
||||
}
|
||||
}
|
||||
// Get userMetadata from target content as well
|
||||
if urls.TargetContent.UserMetadata != nil {
|
||||
for k, v := range urls.TargetContent.UserMetadata {
|
||||
metadata[k] = v
|
||||
}
|
||||
}
|
||||
if srcSSE != nil {
|
||||
delete(metadata, "X-Amz-Server-Side-Encryption-Customer-Algorithm")
|
||||
delete(metadata, "X-Amz-Server-Side-Encryption-Customer-Key-Md5")
|
||||
|
||||
+51
-1
@@ -20,6 +20,7 @@ import (
|
||||
"bufio"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
@@ -57,9 +58,16 @@ var (
|
||||
Name: "encrypt",
|
||||
Usage: "encrypt/decrypt objects (using server-side encryption with server managed keys)",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "attr",
|
||||
Usage: "add custom metadata for the object",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
// ErrInvalidMetadata reflects invalid metadata format
|
||||
var ErrInvalidMetadata = errors.New("specified metadata should be of form key1=value1,key2=value2,... and so on")
|
||||
|
||||
// Copy command.
|
||||
var cpCmd = cli.Command{
|
||||
Name: "cp",
|
||||
@@ -107,7 +115,14 @@ EXAMPLES:
|
||||
|
||||
9. Copy a folder with encrypted objects recursively from Amazon S3 to Minio cloud storage.
|
||||
$ {{.HelpName}} --recursive --encrypt-key "s3/documents/=32byteslongsecretkeymustbegiven1,myminio/documents/=32byteslongsecretkeymustbegiven2" s3/documents/ myminio/documents/
|
||||
`,
|
||||
|
||||
10. Copy a list of objects from local file system to Minio cloud storage with specified metadata.
|
||||
$ {{.HelpName}} --attr key1=value1,key2=value2 Music/*.mp4 play/mybucket/
|
||||
|
||||
11. Copy a folder recursively from Minio cloud storage to Amazon S3 cloud storage with specified metadata.
|
||||
$ {{.HelpName}} --attr key1=value1,key2=value2 --recursive play/mybucket/burningman2011/ s3/mybucket/
|
||||
|
||||
`,
|
||||
}
|
||||
|
||||
// copyMessage container for file copy messages
|
||||
@@ -368,6 +383,19 @@ func doCopySession(session *sessionV8, encKeyDB map[string][]prefixSSEPair) erro
|
||||
cpURLs.TargetContent.Metadata["X-Amz-Storage-Class"] = session.Header.CommandStringFlags["storage-class"]
|
||||
}
|
||||
|
||||
// metaMap, metaSet := session.Header.UserMetaData
|
||||
|
||||
// Check and handle metadata if passed in command line args
|
||||
|
||||
if len(session.Header.UserMetaData) != 0 {
|
||||
if cpURLs.TargetContent.UserMetadata == nil {
|
||||
cpURLs.TargetContent.UserMetadata = make(map[string]string)
|
||||
}
|
||||
for metaDataKey, metaDataVal := range session.Header.UserMetaData {
|
||||
cpURLs.TargetContent.UserMetadata[metaDataKey] = metaDataVal
|
||||
}
|
||||
}
|
||||
|
||||
// Verify if previously copied, notify progress bar.
|
||||
if isCopied(cpURLs.SourceContent.URL.String()) {
|
||||
queueCh <- func() URLs {
|
||||
@@ -439,12 +467,33 @@ loop:
|
||||
return retErr
|
||||
}
|
||||
|
||||
// validate the passed metadataString and populate the map
|
||||
func getMetaDataEntry(metadataString string) (map[string]string, *probe.Error) {
|
||||
metaDataMap := make(map[string]string)
|
||||
for _, metaData := range strings.Split(metadataString, ",") {
|
||||
metaDataEntry := strings.Split(metaData, "=")
|
||||
if len(metaDataEntry) == 2 {
|
||||
metaDataMap[metaDataEntry[0]] = metaDataEntry[1]
|
||||
} else {
|
||||
return nil, probe.NewError(ErrInvalidMetadata)
|
||||
}
|
||||
}
|
||||
return metaDataMap, nil
|
||||
}
|
||||
|
||||
// mainCopy is the entry point for cp command.
|
||||
func mainCopy(ctx *cli.Context) error {
|
||||
// Parse encryption keys per command.
|
||||
encKeyDB, err := getEncKeys(ctx)
|
||||
fatalIf(err, "Unable to parse encryption keys.")
|
||||
|
||||
// Parse metadata.
|
||||
userMetaMap := make(map[string]string)
|
||||
if ctx.String("attr") != "" {
|
||||
userMetaMap, err = getMetaDataEntry(ctx.String("attr"))
|
||||
fatalIf(err, "Unable to parse attribute %v", ctx.String("attr"))
|
||||
}
|
||||
|
||||
// check 'copy' cli arguments.
|
||||
checkCopySyntax(ctx, encKeyDB)
|
||||
|
||||
@@ -469,6 +518,7 @@ func mainCopy(ctx *cli.Context) error {
|
||||
session.Header.CommandStringFlags["storage-class"] = storageClass
|
||||
session.Header.CommandStringFlags["encrypt-key"] = sseKeys
|
||||
session.Header.CommandStringFlags["encrypt"] = sse
|
||||
session.Header.UserMetaData = userMetaMap
|
||||
|
||||
var e error
|
||||
if session.Header.RootPath, e = os.Getwd(); e != nil {
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
/*
|
||||
* Minio Client (C) 2019 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 (
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestParseMetaData(t *testing.T) {
|
||||
metaDataCases := []struct {
|
||||
input string
|
||||
output map[string]string
|
||||
err error
|
||||
status bool
|
||||
}{
|
||||
// success scenerio
|
||||
{"key1=value1,key2=value2", map[string]string{"key1": "value1", "key2": "value2"}, nil, true},
|
||||
// using different delimitter, other than ',' between multiple meta data
|
||||
{"key1=value1;key2=value2", nil, ErrInvalidMetadata, false},
|
||||
// using different delimitter, other than '=' between key value
|
||||
{"key1:value1,key2:value2", nil, ErrInvalidMetadata, false},
|
||||
// using no delimitter
|
||||
{"key1:value1:key2:value2", nil, ErrInvalidMetadata, false},
|
||||
}
|
||||
|
||||
for idx, testCase := range metaDataCases {
|
||||
metaDatamap, errMeta := getMetaDataEntry(testCase.input)
|
||||
if testCase.status == true {
|
||||
if errMeta != nil {
|
||||
t.Fatalf("Test %d: generated error not matching, expected = `%s`, found = `%s`", idx+1, testCase.err, errMeta)
|
||||
}
|
||||
if !reflect.DeepEqual(metaDatamap, testCase.output) {
|
||||
t.Fatalf("Test %d: generated Map not matching, expected = `%s`, found = `%s`", idx+1, testCase.input, metaDatamap)
|
||||
}
|
||||
}
|
||||
|
||||
if testCase.status == false {
|
||||
if !reflect.DeepEqual(metaDatamap, testCase.output) {
|
||||
t.Fatalf("Test %d: generated Map not matching, expected = `%s`, found = `%s`", idx+1, testCase.input, metaDatamap)
|
||||
}
|
||||
if errMeta.Cause.Error() != testCase.err.Error() {
|
||||
t.Fatalf("Test %d: generated error not matching, expected = `%s`, found = `%s`", idx+1, testCase.err, errMeta)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -50,6 +50,7 @@ type sessionV8Header struct {
|
||||
LastRemoved string `json:"lastRemoved"`
|
||||
TotalBytes int64 `json:"totalBytes"`
|
||||
TotalObjects int64 `json:"totalObjects"`
|
||||
UserMetaData map[string]string `json:"metaData"`
|
||||
}
|
||||
|
||||
// sessionMessage container for session messages
|
||||
@@ -174,6 +175,7 @@ func newSessionV8() *sessionV8 {
|
||||
s.Header.CommandBoolFlags = make(map[string]bool)
|
||||
s.Header.CommandIntFlags = make(map[string]int)
|
||||
s.Header.CommandStringFlags = make(map[string]string)
|
||||
s.Header.UserMetaData = make(map[string]string)
|
||||
s.Header.When = UTCNow()
|
||||
s.mutex = new(sync.Mutex)
|
||||
s.SessionID = newRandomID(8)
|
||||
|
||||
+16
-1
@@ -334,6 +334,21 @@ function test_put_object_with_storage_class_error()
|
||||
log_success "$start_time" "${FUNCNAME[0]}"
|
||||
}
|
||||
|
||||
## Test mc cp command with valid metadata string
|
||||
function test_put_object_with_metadata()
|
||||
{
|
||||
show "${FUNCNAME[0]}"
|
||||
|
||||
start_time=$(get_time)
|
||||
object_name="mc-test-object-$RANDOM"
|
||||
assert_success "$start_time" "${FUNCNAME[0]}" mc_cmd cp --attr key1=val1,key2=val2 "${FILE_1_MB}" "${SERVER_ALIAS}/${BUCKET_NAME}/${object_name}"
|
||||
diff -bB <(echo "val1") <("${MC_CMD[@]}" --json stat "${SERVER_ALIAS}/${BUCKET_NAME}/${object_name}" | jq -r '.metadata."X-Amz-Meta-Key1"') >/dev/null 2>&1
|
||||
assert_success "$start_time" "${FUNCNAME[0]}" show_on_failure $? "unable to put object with metadata"
|
||||
assert_success "$start_time" "${FUNCNAME[0]}" mc_cmd rm "${SERVER_ALIAS}/${BUCKET_NAME}/${object_name}"
|
||||
log_success "$start_time" "${FUNCNAME[0]}"
|
||||
|
||||
}
|
||||
|
||||
function test_get_object()
|
||||
{
|
||||
show "${FUNCNAME[0]}"
|
||||
@@ -805,12 +820,12 @@ function run_test()
|
||||
test_make_bucket_error
|
||||
|
||||
setup
|
||||
|
||||
test_put_object
|
||||
test_put_object_error
|
||||
test_put_object_0byte
|
||||
test_put_object_with_storage_class
|
||||
test_put_object_with_storage_class_error
|
||||
test_put_object_with_metadata
|
||||
test_put_object_multipart
|
||||
test_get_object
|
||||
test_get_object_multipart
|
||||
|
||||
Reference in New Issue
Block a user