diff --git a/cmd/client-errors.go b/cmd/client-errors.go index 5e6f0ed9..78e3dcb4 100644 --- a/cmd/client-errors.go +++ b/cmd/client-errors.go @@ -56,6 +56,13 @@ func (e BucketNameEmpty) Error() string { return "Bucket name cannot be empty." } +// ObjectNameEmpty - object name empty. +type ObjectNameEmpty struct{} + +func (e ObjectNameEmpty) Error() string { + return "Object name cannot be empty." +} + // BucketInvalid - bucket name invalid. type BucketInvalid struct { Bucket string diff --git a/cmd/client-fs.go b/cmd/client-fs.go index e20ca762..ac4a2209 100644 --- a/cmd/client-fs.go +++ b/cmd/client-fs.go @@ -40,6 +40,7 @@ import ( "github.com/minio/mc/pkg/probe" minio "github.com/minio/minio-go/v6" "github.com/minio/minio-go/v6/pkg/encrypt" + "github.com/minio/minio/pkg/bucket/object/tagging" ) // filesystem client @@ -1089,3 +1090,27 @@ func (f *fsClient) fsStat(isIncomplete bool) (os.FileInfo, *probe.Error) { func (f *fsClient) AddUserAgent(_, _ string) { } + +// Get Object Tags +func (f *fsClient) GetObjectTagging() (tagging.Tagging, *probe.Error) { + return tagging.Tagging{}, probe.NewError(APINotImplemented{ + API: "GetObjectTagging", + APIType: "filesystem", + }) +} + +// Set Object tags +func (f *fsClient) SetObjectTagging(tagMap map[string]string) *probe.Error { + return probe.NewError(APINotImplemented{ + API: "SetObjectTagging", + APIType: "filesystem", + }) +} + +// Delete object tags +func (f *fsClient) DeleteObjectTagging() *probe.Error { + return probe.NewError(APINotImplemented{ + API: "DeleteObjectTagging", + APIType: "filesystem", + }) +} diff --git a/cmd/client-s3.go b/cmd/client-s3.go index 1e56da03..9c63805e 100644 --- a/cmd/client-s3.go +++ b/cmd/client-s3.go @@ -21,6 +21,7 @@ import ( "context" "crypto/tls" "encoding/json" + "encoding/xml" "errors" "hash/fnv" "io" @@ -42,6 +43,7 @@ import ( "github.com/minio/minio-go/v6/pkg/encrypt" "github.com/minio/minio-go/v6/pkg/policy" "github.com/minio/minio-go/v6/pkg/s3utils" + "github.com/minio/minio/pkg/bucket/object/tagging" "github.com/minio/minio/pkg/mimedb" ) @@ -2074,3 +2076,55 @@ func (c *s3Client) GetObjectLockConfig() (mode *minio.RetentionMode, validity *u return mode, validity, unit, nil } + +// Get Object Tags +func (c *s3Client) GetObjectTagging() (tagging.Tagging, *probe.Error) { + var err error + bucketName, objectName := c.url2BucketAndObject() + if bucketName == "" { + return tagging.Tagging{}, probe.NewError(BucketNameEmpty{}) + } + if objectName == "" { + return tagging.Tagging{}, probe.NewError(ObjectNameEmpty{}) + } + tagXML, err := c.api.GetObjectTagging(bucketName, objectName) + if err != nil { + return tagging.Tagging{}, probe.NewError(err) + } + var tagObj tagging.Tagging + if err = xml.Unmarshal([]byte(tagXML), &tagObj); err != nil { + return tagging.Tagging{}, probe.NewError(err) + } + return tagObj, nil +} + +// Set Object tags +func (c *s3Client) SetObjectTagging(tagMap map[string]string) *probe.Error { + var err error + bucketName, objectName := c.url2BucketAndObject() + if bucketName == "" { + return probe.NewError(BucketNameEmpty{}) + } + if objectName == "" { + return probe.NewError(ObjectNameEmpty{}) + } + if err = c.api.PutObjectTagging(bucketName, objectName, tagMap); err != nil { + return probe.NewError(err) + } + return nil +} + +// Delete object tags +func (c *s3Client) DeleteObjectTagging() *probe.Error { + bucketName, objectName := c.url2BucketAndObject() + if bucketName == "" { + return probe.NewError(BucketNameEmpty{}) + } + if objectName == "" { + return probe.NewError(ObjectNameEmpty{}) + } + if err := c.api.RemoveObjectTagging(bucketName, objectName); err != nil { + return probe.NewError(err) + } + return nil +} diff --git a/cmd/client.go b/cmd/client.go index 0133213a..1f4c2949 100644 --- a/cmd/client.go +++ b/cmd/client.go @@ -25,6 +25,7 @@ import ( "github.com/minio/mc/pkg/probe" minio "github.com/minio/minio-go/v6" "github.com/minio/minio-go/v6/pkg/encrypt" + "github.com/minio/minio/pkg/bucket/object/tagging" ) // DirOpt - list directory option. @@ -84,6 +85,11 @@ type Client interface { GetURL() clientURL AddUserAgent(app, version string) + + // Object Tag operations + GetObjectTagging() (tagging.Tagging, *probe.Error) + SetObjectTagging(tagMap map[string]string) *probe.Error + DeleteObjectTagging() *probe.Error } // Content container for content metadata diff --git a/cmd/main.go b/cmd/main.go index 9258b780..090f9354 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -334,6 +334,7 @@ var appCmds = []cli.Command{ eventCmd, watchCmd, policyCmd, + tagCmd, adminCmd, configCmd, updateCmd, diff --git a/cmd/tag-list.go b/cmd/tag-list.go new file mode 100644 index 00000000..6c132162 --- /dev/null +++ b/cmd/tag-list.go @@ -0,0 +1,212 @@ +/* + * MinIO Client (C) 2020 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 ( + "bytes" + "errors" + "fmt" + "os" + "path/filepath" + "strings" + + "github.com/fatih/color" + "github.com/minio/cli" + json "github.com/minio/mc/pkg/colorjson" + "github.com/minio/mc/pkg/probe" + "github.com/minio/minio/pkg/bucket/object/tagging" + "github.com/minio/minio/pkg/console" +) + +var tagListCmd = cli.Command{ + Name: "list", + Usage: "list tags for an object", + Action: mainListTag, + Before: setGlobalsFromContext, + Flags: globalFlags, + CustomHelpTemplate: `Name: + {{.HelpName}} - {{.Usage}} + +USAGE: + {{.HelpName}} [COMMAND FLAGS] TARGET + +FLAGS: + {{range .VisibleFlags}}{{.}} + {{end}} +DESCRIPTION: + List tags assigned to an object. + +EXAMPLES: + 1. List the tags assigned to an object. + {{.Prompt}} {{.HelpName}} s3/testbucket/testobject + 2. List the tags assigned to an object in JSON format. + {{.Prompt}} {{.HelpName}} --json s3/testbucket/testobject + +`, +} + +const ( + tagMainHeader string = "Main-Heading" + tagRowTheme string = "Row-Header" + tagPrintMsgTheme string = "Tag-PrintMsg" + tagPrintErrMsgTheme string = "Tag-PrintMsgErr" +) + +type tagList struct { + Key string `json:"Key"` + Value string `json:"Value"` +} + +// tagsetListMessage container for displaying tag +type tagsetListMessage struct { + Tags []tagList `json:"tagset,omitempty"` + Status string `json:"status"` + URL string `json:"url"` + Error error `json:"error,omitempty"` + TagObj tagging.Tagging `json:"-"` +} + +func (t tagsetListMessage) JSON() string { + if t.Error == nil && len(t.Tags) == 0 { + errorIf(probe.NewError(errors.New("Tag(s) not set for "+t.URL)), "Failed to get tags.") + } else { + tagJSONbytes, err := json.MarshalIndent(t, "", " ") + tagJSONbytes = bytes.Replace(tagJSONbytes, []byte("\\u0026"), []byte("&"), -1) + fatalIf(probe.NewError(err), "Unable to marshal into JSON for "+getTagObjectName(t.URL)) + return string(tagJSONbytes) + } + return "" +} + +func (t tagsetListMessage) String() string { + if t.Error != nil { + return console.Colorize(tagPrintErrMsgTheme, "Failed to get tags for "+t.URL+". "+t.Error.Error()) + } + if len(t.Tags) == 0 { + return console.Colorize(tagPrintMsgTheme, "Tag(s) not set for "+t.URL+". ") + } + return getFormattedTagList(getTagObjectName(t.URL), t.TagObj.TagSet.Tags) +} + +// getnTagListMessage parses the tags(string) and initializes the structure tagsetListMessage. +// tags(string) is in the format key1=value1&key1=value2 +func getTagListMessage(tags tagging.Tagging, urlStr string, err error) tagsetListMessage { + var t tagsetListMessage + var tagStr string + var kvPairStr []string + tagStr = strings.Replace(tags.String(), "\\u0026", "&", -1) + t.URL = urlStr + t.TagObj = tags + t.Error = nil + if tagStr != "" { + kvPairStr = strings.SplitN(tagStr, "&", -1) + t.Status = "success" + } else { + t.Status = "error" + t.Error = err + } + for _, kvPair := range kvPairStr { + kvPairSplit := splitStr(kvPair, "=", 2) + t.Tags = append(t.Tags, tagList{Key: kvPairSplit[0], Value: kvPairSplit[1]}) + } + + return t +} + +func getObjTagging(urlStr string) (tagging.Tagging, error) { + clnt, pErr := newClient(urlStr) + if pErr != nil { + fatalIf(pErr.Trace(urlStr), "Unable to initialize target "+urlStr+". "+pErr.ToGoError().Error()) + } + tagObj, pErr := clnt.GetObjectTagging() + fatalIf(pErr, "Failed to get tags for "+urlStr) + + return tagObj, nil +} + +// Color scheme for tag display +func setTagListColorScheme() { + console.SetColor(tagRowTheme, color.New(color.FgWhite)) + console.SetColor(tagMainHeader, color.New(color.Bold, color.FgCyan)) + console.SetColor(tagPrintMsgTheme, color.New(color.FgGreen)) + console.SetColor(tagPrintErrMsgTheme, color.New(color.FgRed)) +} + +func checkListTagSyntax(ctx *cli.Context) { + if len(ctx.Args()) != 1 { + cli.ShowCommandHelp(ctx, "list") + os.Exit(globalErrorExitStatus) + } +} + +func getTagObjectName(urlStr string) string { + if !strings.Contains(urlStr, "/") { + urlStr = filepath.ToSlash(urlStr) + } + splits := splitStr(urlStr, "/", 3) + object := splits[2] + + return object +} + +func getFormattedTagList(tagObjName string, kvpairs []tagging.Tag) string { + var tagListInfo string + padLen := len("Name") + for _, kv := range kvpairs { + if len(kv.Key) > padLen { + padLen = len(kv.Key) + } + } + padLen = listTagPaddingSpace(padLen) + objectName := fmt.Sprintf("%-*s: %s\n", padLen, "Name", tagObjName) + tagListInfo += console.Colorize(tagMainHeader, objectName) + for idx := 0; idx < len(kvpairs); idx++ { + displayField := fmt.Sprintf("%-*s: %s\n", padLen, kvpairs[idx].Key, kvpairs[idx].Value) + tagListInfo += console.Colorize(tagRowTheme, displayField) + } + return tagListInfo +} + +func listTagPaddingSpace(padLen int) int { + switch padLen % 4 { + case 0: + padLen += 4 + case 1: + padLen += 3 + case 2: + padLen += 2 + case 3: + padLen += 5 + } + return padLen +} + +func mainListTag(ctx *cli.Context) error { + checkListTagSyntax(ctx) + setTagListColorScheme() + args := ctx.Args() + objectURL := args.Get(0) + var tagObj tagging.Tagging + var err error + if tagObj, err = getObjTagging(objectURL); err != nil { + fatal(probe.NewError(err), "Unable to get tags for target "+objectURL+".") + } + var msg tagsetListMessage + msg = getTagListMessage(tagObj, objectURL, err) + printMsg(msg) + return nil +} diff --git a/cmd/tag-main.go b/cmd/tag-main.go new file mode 100644 index 00000000..663c856b --- /dev/null +++ b/cmd/tag-main.go @@ -0,0 +1,43 @@ +/* + * MinIO Client (C) 2020 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 ( + "github.com/minio/cli" +) + +var tagCmd = cli.Command{ + Name: "tag", + Usage: "manage tags for an object", + Action: mainTag, + Before: setGlobalsFromContext, + Flags: globalFlags, + Subcommands: []cli.Command{ + tagListCmd, + tagRemoveCmd, + tagSetCmd, + }, +} + +func checkMainTagSyntax(ctx *cli.Context) { + cli.ShowCommandHelp(ctx, "") +} + +func mainTag(ctx *cli.Context) error { + checkMainTagSyntax(ctx) + return nil +} diff --git a/cmd/tag-remove.go b/cmd/tag-remove.go new file mode 100644 index 00000000..9f4ff15b --- /dev/null +++ b/cmd/tag-remove.go @@ -0,0 +1,106 @@ +/* + * MinIO Client (C) 2020 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 ( + "os" + + "github.com/minio/cli" + json "github.com/minio/mc/pkg/colorjson" + "github.com/minio/mc/pkg/probe" + "github.com/minio/minio/pkg/console" +) + +var tagRemoveCmd = cli.Command{ + Name: "remove", + Usage: "remove tags assigned to an object", + Action: mainRemoveTag, + Before: setGlobalsFromContext, + Flags: globalFlags, + CustomHelpTemplate: `Name: + {{.HelpName}} - {{.Usage}} + +USAGE: + {{.HelpName}} [COMMAND FLAGS] TARGET + +FLAGS: + {{range .VisibleFlags}}{{.}} + {{end}} +DESCRIPTION: + Remove object tags assigned to an object . + +EXAMPLES: + 1. Remove the tags set to an existing object. + {{.Prompt}} {{.HelpName}} s3/testbucket/testobject + +`, +} + +// tagSetTagMessage structure will show message depending on the type of console. +type tagRemoveMessage struct { + Status string `json:"status"` + Name string `json:"name"` + Error error `json:"error,omitempty"` +} + +// tagRemoveMessage console colorized output. +func (t tagRemoveMessage) String() string { + return console.Colorize(tagPrintMsgTheme, "Tags removed for "+t.Name+".") +} + +// JSON tagRemoveMessage. +func (t tagRemoveMessage) JSON() string { + msgBytes, e := json.MarshalIndent(t, "", " ") + fatalIf(probe.NewError(e), "Unable to marshal into JSON.") + return string(msgBytes) +} + +func getTagRemoveMessage(tags string, urlStr string, err error) tagRemoveMessage { + var t tagRemoveMessage + t.Name = getTagObjectName(urlStr) + if err != nil { + t.Status = "error" + t.Error = err + } else { + t.Status = "success" + } + return t +} + +func checkRemoveTagSyntax(ctx *cli.Context) { + if len(ctx.Args()) != 1 { + cli.ShowCommandHelp(ctx, "remove") + os.Exit(globalErrorExitStatus) + } +} + +func mainRemoveTag(ctx *cli.Context) error { + checkRemoveTagSyntax(ctx) + setTagListColorScheme() + var pErr *probe.Error + var msg tagRemoveMessage + objectURL := ctx.Args().Get(0) + clnt, pErr := newClient(objectURL) + fatalIf(pErr.Trace(objectURL), "Unable to initialize target "+objectURL+".") + pErr = clnt.DeleteObjectTagging() + fatalIf(pErr.Trace(objectURL), "Failed to remove tags") + tagObj, err := getObjTagging(objectURL) + msg = getTagRemoveMessage(tagObj.String(), objectURL, err) + printMsg(msg) + + return nil +} diff --git a/cmd/tag-set.go b/cmd/tag-set.go new file mode 100644 index 00000000..449b3912 --- /dev/null +++ b/cmd/tag-set.go @@ -0,0 +1,141 @@ +/* + * MinIO Client (C) 2020 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 ( + "errors" + "os" + "strconv" + "strings" + + "github.com/minio/cli" + json "github.com/minio/mc/pkg/colorjson" + "github.com/minio/mc/pkg/probe" + "github.com/minio/minio/pkg/console" +) + +var tagSetCmd = cli.Command{ + Name: "set", + Usage: "set tags for an object", + Action: mainSetTag, + Before: setGlobalsFromContext, + Flags: globalFlags, + CustomHelpTemplate: `Name: + {{.HelpName}} - {{.Usage}} + +USAGE: + {{.HelpName}} [COMMAND FLAGS] TARGET [TAGS] + +FLAGS: + {{range .VisibleFlags}}{{.}} + {{end}} +DESCRIPTION: + Assign object tags (key,value) to target. + +EXAMPLES: + 1. Assign the tags to an existing object. + {{.Prompt}} {{.HelpName}} s3/testbucket/testobject "key1=value1&key2=value2&key3=value3" + +`, +} + +// tagSetTagMessage structure will show message depending on the type of console. +type tagSetMessage struct { + Status string `json:"status"` + Name string `json:"name"` + Error error `json:"error,omitempty"` +} + +// tagSetMessage console colorized output. +func (t tagSetMessage) String() string { + return console.Colorize(tagPrintMsgTheme, "Tags set for "+t.Name+".") +} + +// JSON tagSetMessage. +func (t tagSetMessage) JSON() string { + msgBytes, e := json.MarshalIndent(t, "", " ") + fatalIf(probe.NewError(e), "Unable to marshal into JSON.") + return string(msgBytes) +} + +func getTagSetMessage(tags string, urlStr string, err error) tagSetMessage { + var t tagSetMessage + t.Name = getTagObjectName(urlStr) + if err != nil { + t.Status = "error" + t.Error = err + } else { + t.Status = "success" + } + return t +} + +func checkSetTagSyntax(ctx *cli.Context) { + if len(ctx.Args()) != 2 || (len(ctx.Args()) == 2 && len(ctx.Args().Get(1)) == 0) { + cli.ShowCommandHelp(ctx, "set") + os.Exit(globalErrorExitStatus) + } +} + +func getTaggingMap(ctx *cli.Context) (map[string]string, error) { + if len(ctx.Args()) != 2 { + return nil, errors.New("Tags argument is empty") + } + tagKVMap := make(map[string]string) + tagValues := strings.Split(ctx.Args().Get(1), "&") + for tagIdx, tag := range tagValues { + var key, val string + if !strings.Contains(tag, "=") { + key = tag + val = "" + } else { + key = splitStr(tag, "=", 2)[0] + val = splitStr(tag, "=", 2)[1] + } + if key != "" { + tagKVMap[key] = val + } else { + return nil, errors.New("error extracting tag argument(#" + strconv.Itoa(tagIdx+1) + ") " + tag) + } + } + return tagKVMap, nil +} + +func mainSetTag(ctx *cli.Context) error { + checkSetTagSyntax(ctx) + setTagListColorScheme() + objectURL := ctx.Args().Get(0) + var err error + var pErr *probe.Error + var objTagMap map[string]string + var msg tagSetMessage + + if objTagMap, err = getTaggingMap(ctx); err != nil { + fatalIf(probe.NewError(err), ". Key value parsing failed from arguments provided. Please refer to mc "+ctx.Command.FullName()+" --help for details.") + } + clnt, pErr := newClient(objectURL) + if pErr != nil { + fatalIf(pErr.Trace(objectURL), "Unable to initialize target "+objectURL+". "+pErr.ToGoError().Error()) + } + pErr = clnt.SetObjectTagging(objTagMap) + fatalIf(pErr, "Failed to set tags") + tagObj, err := getObjTagging(objectURL) + msg = getTagSetMessage(tagObj.String(), objectURL, err) + printMsg(msg) + + return nil +}