Add metadata and tags to mc find (#4531)

This commit is contained in:
Klaus Post
2023-04-08 09:43:27 -07:00
committed by GitHub
parent 2c3f0e8ccf
commit 36aa65b791
8 changed files with 110 additions and 48 deletions
+13 -12
View File
@@ -1510,7 +1510,7 @@ func (c *S3Client) SetAccess(ctx context.Context, bucketPolicy string, isJSON bo
// listObjectWrapper - select ObjectList mode depending on arguments
func (c *S3Client) listObjectWrapper(ctx context.Context, bucket, object string, isRecursive bool, timeRef time.Time, withVersions, withDeleteMarkers bool, metadata bool, maxKeys int, zip bool) <-chan minio.ObjectInfo {
if !timeRef.IsZero() || withVersions {
return c.listVersions(ctx, bucket, object, isRecursive, timeRef, withVersions, withDeleteMarkers)
return c.listVersions(ctx, bucket, object, ListOptions{Recursive: isRecursive, TimeRef: timeRef, WithOlderVersions: withVersions, WithDeleteMarkers: withDeleteMarkers})
}
if isGoogle(c.targetURL.Host) {
@@ -1742,16 +1742,16 @@ func (c *S3Client) splitPath(path string) (bucketName, objectName string) {
/// Bucket API operations.
func (c *S3Client) listVersions(ctx context.Context, b, o string, isRecursive bool, timeRef time.Time, includeOlderVersions, withDeleteMarkers bool) chan minio.ObjectInfo {
func (c *S3Client) listVersions(ctx context.Context, b, o string, opts ListOptions) chan minio.ObjectInfo {
objectInfoCh := make(chan minio.ObjectInfo)
go func() {
defer close(objectInfoCh)
c.listVersionsRoutine(ctx, b, o, isRecursive, timeRef, includeOlderVersions, withDeleteMarkers, objectInfoCh)
c.listVersionsRoutine(ctx, b, o, opts, objectInfoCh)
}()
return objectInfoCh
}
func (c *S3Client) listVersionsRoutine(ctx context.Context, b, o string, isRecursive bool, timeRef time.Time, includeOlderVersions, withDeleteMarkers bool, objectInfoCh chan minio.ObjectInfo) {
func (c *S3Client) listVersionsRoutine(ctx context.Context, b, o string, opts ListOptions, objectInfoCh chan minio.ObjectInfo) {
var buckets []string
if b == "" {
bucketsInfo, err := c.api.ListBuckets(ctx)
@@ -1775,8 +1775,9 @@ func (c *S3Client) listVersionsRoutine(ctx context.Context, b, o string, isRecur
var skipKey string
for objectVersion := range c.api.ListObjects(ctx, b, minio.ListObjectsOptions{
Prefix: o,
Recursive: isRecursive,
Recursive: opts.Recursive,
WithVersions: true,
WithMetadata: opts.WithMetadata,
}) {
if objectVersion.Err != nil {
select {
@@ -1787,17 +1788,17 @@ func (c *S3Client) listVersionsRoutine(ctx context.Context, b, o string, isRecur
continue
}
if !includeOlderVersions && skipKey == objectVersion.Key {
if !opts.WithOlderVersions && skipKey == objectVersion.Key {
// Skip current version if not asked to list all versions
// and we already listed the current object key name
continue
}
if timeRef.IsZero() || objectVersion.LastModified.Before(timeRef) {
if opts.TimeRef.IsZero() || objectVersion.LastModified.Before(opts.TimeRef) {
skipKey = objectVersion.Key
// Skip if this is a delete marker and we are not asked to list it
if !withDeleteMarkers && objectVersion.IsDeleteMarker {
if !opts.WithDeleteMarkers && objectVersion.IsDeleteMarker {
continue
}
@@ -1856,8 +1857,7 @@ func (c *S3Client) versionedList(ctx context.Context, contentCh chan *ClientCont
case contentCh <- c.bucketInfo2ClientContent(bucket):
}
}
for objectVersion := range c.listVersions(ctx, bucket.Name, "",
opts.Recursive, opts.TimeRef, opts.WithOlderVersions, opts.WithDeleteMarkers) {
for objectVersion := range c.listVersions(ctx, bucket.Name, "", opts) {
if objectVersion.Err != nil {
if minio.ToErrorResponse(objectVersion.Err).Code == "NotImplemented" {
goto noVersioning
@@ -1888,8 +1888,7 @@ func (c *S3Client) versionedList(ctx context.Context, contentCh chan *ClientCont
}
return
default:
for objectVersion := range c.listVersions(ctx, b, o,
opts.Recursive, opts.TimeRef, opts.WithOlderVersions, opts.WithDeleteMarkers) {
for objectVersion := range c.listVersions(ctx, b, o, opts) {
if objectVersion.Err != nil {
if minio.ToErrorResponse(objectVersion.Err).Code == "NotImplemented" {
goto noVersioning
@@ -2177,6 +2176,8 @@ func (c *S3Client) objectInfo2ClientContent(bucket string, entry minio.ObjectInf
content.Restore = entry.Restore
content.Metadata = map[string]string{}
content.UserMetadata = map[string]string{}
content.Tags = entry.UserTags
content.ReplicationStatus = entry.ReplicationStatus
for k, v := range entry.UserMetadata {
content.UserMetadata[k] = v
+1
View File
@@ -189,6 +189,7 @@ type ClientContent struct {
Type os.FileMode
StorageClass string
Metadata map[string]string
Tags map[string]string
UserMetadata map[string]string
ETag string
Expires time.Time
+21 -4
View File
@@ -19,10 +19,11 @@ package cmd
import (
"context"
"regexp"
"strings"
"time"
humanize "github.com/dustin/go-humanize"
"github.com/dustin/go-humanize"
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/mc/pkg/probe"
@@ -66,7 +67,7 @@ var (
},
cli.StringFlag{
Name: "regex",
Usage: "match directory and object name with PCRE regex pattern",
Usage: "match directory and object name with RE2 regex pattern",
},
cli.StringFlag{
Name: "larger",
@@ -84,6 +85,14 @@ var (
Name: "watch",
Usage: "monitor a specified path for newly created object(s)",
},
cli.StringSliceFlag{
Name: "metadata",
Usage: "match metadata with RE2 regex pattern. Specify each with key=regex. MinIO server only.",
},
cli.StringSliceFlag{
Name: "tags",
Usage: "match tags with RE2 regex pattern. Specify each with key=regex. MinIO server only.",
},
}
)
@@ -202,7 +211,7 @@ type findContext struct {
ignorePattern string
namePattern string
pathPattern string
regexPattern string
regexPattern *regexp.Regexp
maxDepth uint
printFmt string
olderThan string
@@ -211,6 +220,8 @@ type findContext struct {
smallerSize uint64
watch bool
withOlderVersions bool
matchMeta map[string]*regexp.Regexp
matchTags map[string]*regexp.Regexp
// Internal values
targetAlias string
@@ -278,6 +289,10 @@ func mainFind(cliCtx *cli.Context) error {
if hostCfg != nil {
targetFullURL = hostCfg.URL
}
var regMatch *regexp.Regexp
if cliCtx.String("regex") != "" {
regMatch = regexp.MustCompile(cliCtx.String("regex"))
}
return doFind(ctx, &findContext{
Context: cliCtx,
@@ -286,7 +301,7 @@ func mainFind(cliCtx *cli.Context) error {
printFmt: cliCtx.String("print"),
namePattern: cliCtx.String("name"),
pathPattern: cliCtx.String("path"),
regexPattern: cliCtx.String("regex"),
regexPattern: regMatch,
ignorePattern: cliCtx.String("ignore"),
withOlderVersions: withVersions,
olderThan: olderThan,
@@ -298,5 +313,7 @@ func mainFind(cliCtx *cli.Context) error {
targetURL: args[0],
targetFullURL: targetFullURL,
clnt: clnt,
matchMeta: getRegexMap(cliCtx, "metadata"),
matchTags: getRegexMap(cliCtx, "tags"),
})
}
+62 -10
View File
@@ -20,6 +20,7 @@ package cmd
import (
"bytes"
"context"
"fmt"
"os"
"os/exec"
"path/filepath"
@@ -31,6 +32,7 @@ import (
"github.com/dustin/go-humanize"
"github.com/google/shlex"
"github.com/minio/cli"
"github.com/minio/mc/pkg/probe"
"github.com/minio/pkg/console"
@@ -109,13 +111,6 @@ func pathMatch(pattern, path string) bool {
return wildcard.Match(pattern, path)
}
// regexMatch reports whether path matches the regex pattern.
func regexMatch(pattern, path string) bool {
matched, e := regexp.MatchString(pattern, path)
errorIf(probe.NewError(e).Trace(pattern), "Unable to regex match with input pattern.")
return matched
}
func getExitStatus(err error) int {
if err == nil {
return 0
@@ -280,6 +275,7 @@ func doFind(ctxCtx context.Context, ctx *findContext) error {
WithDeleteMarkers: false,
Recursive: true,
ShowDir: DirFirst,
WithMetadata: len(ctx.matchMeta) > 0 || len(ctx.matchTags) > 0,
}
// iterate over all content which is within the given directory
@@ -313,6 +309,8 @@ func doFind(ctxCtx context.Context, ctx *findContext) error {
VersionID: content.VersionID,
Time: content.Time.Local(),
Size: content.Size,
Metadata: content.UserMetadata,
Tags: content.Tags,
}
// Match the incoming content, didn't match return.
@@ -412,8 +410,8 @@ func matchFind(ctx *findContext, fileContent contentMessage) (match bool) {
if match && ctx.pathPattern != "" {
match = pathMatch(ctx.pathPattern, path)
}
if match && ctx.regexPattern != "" {
match = regexMatch(ctx.regexPattern, path)
if match && ctx.regexPattern != nil {
match = ctx.regexPattern.MatchString(path)
}
if match && ctx.olderThan != "" {
match = !isOlder(fileContent.Time, ctx.olderThan)
@@ -427,6 +425,12 @@ func matchFind(ctx *findContext, fileContent contentMessage) (match bool) {
if match && ctx.smallerSize > 0 {
match = int64(ctx.smallerSize) > fileContent.Size
}
if match && len(ctx.matchMeta) > 0 {
match = matchRegexMaps(ctx.matchMeta, fileContent.Metadata)
}
if match && len(ctx.matchTags) > 0 {
match = matchRegexMaps(ctx.matchTags, fileContent.Tags)
}
return match
}
@@ -445,7 +449,7 @@ func getShareURL(ctx context.Context, path string) string {
content, err := clnt.Stat(ctx, StatOptions{})
fatalIf(err.Trace(targetURLFull, targetAlias), "Unable to lookup file/object.")
// Skip if its a directory.
// Skip if it is a directory.
if content.Type.IsDir() {
return ""
}
@@ -460,3 +464,51 @@ func getShareURL(ctx context.Context, path string) string {
return shareURL
}
// getRegexMap returns a map from the StringSlice key.
// Each entry must be key=regex.
// Will exit with error if an un-parsable entry is found.
func getRegexMap(cliCtx *cli.Context, key string) map[string]*regexp.Regexp {
sl := cliCtx.StringSlice(key)
if len(sl) == 0 {
return nil
}
reMap := make(map[string]*regexp.Regexp, len(sl))
for _, v := range sl {
split := strings.SplitN(v, "=", 2)
if len(split) < 2 {
err := probe.NewError(fmt.Errorf("want one = separator, got none"))
fatalIf(err.Trace(v), "Unable to split key+value. Must be key=regex")
}
// No value means it should not exist or be empty.
if len(split[1]) == 0 {
reMap[split[0]] = nil
continue
}
var err error
reMap[split[0]], err = regexp.Compile(split[1])
if err != nil {
fatalIf(probe.NewError(err), fmt.Sprintf("Unable to compile metadata regex for %s=%s", split[0], split[1]))
}
}
return reMap
}
// matchRegexMaps will check if all regexes in 'm' match values in 'v' with the same key.
// If a regex is nil, it must either not exist in v or have a 0 length value.
func matchRegexMaps(m map[string]*regexp.Regexp, v map[string]string) bool {
for k, reg := range m {
if reg == nil {
if v[k] != "" {
return false
}
// Does not exist or empty, that is fine.
continue
}
val, ok := v[k]
if !ok || !reg.MatchString(val) {
return false
}
}
return true
}
+2 -15
View File
@@ -20,6 +20,7 @@ package cmd
import (
"context"
"os/exec"
"regexp"
"runtime"
"strings"
"testing"
@@ -54,7 +55,7 @@ func TestMatchFind(t *testing.T) {
clnt: &S3Client{
targetURL: &ClientURL{},
},
regexPattern: `^(\d+\.){3}\d+$`,
regexPattern: regexp.MustCompile(`^(\d+\.){3}\d+$`),
},
{
clnt: &S3Client{
@@ -308,14 +309,6 @@ func TestFindMatch(t *testing.T) {
{"*W", "/Word//this/is a/trickyTest", "path", false},
{"LTIxNDc0ODM2NDgvLTE=", "LTIxNDc0ODM2NDgvLTE=/I/Am/One/Baaaaad/String", "path", false},
{"/", "funky/path/name", "path", false},
// Regexp based - success cases.
{"^[a-zA-Z][a-zA-Z0-9\\-]+[a-zA-Z0-9]$", "testbucket-1", "regex", true},
{`^(\d+\.){3}\d+$`, "192.168.1.1", "regex", true},
// Regexp based - failure cases.
{"^[a-zA-Z][a-zA-Z0-9\\-]+[a-zA-Z0-9]$", "testbucket.", "regex", false},
{`^(\d+\.){3}\d+$`, "192.168.x.x", "regex", false},
}
for _, test := range basicTests {
@@ -332,12 +325,6 @@ func TestFindMatch(t *testing.T) {
t.Fatalf("Unexpected result %t, with pattern %s, flag %s and filepath %s \n",
!test.match, test.pattern, test.flagName, test.filePath)
}
case "regex":
testMatch := regexMatch(test.pattern, test.filePath)
if testMatch != test.match {
t.Fatalf("Unexpected result %t, with pattern %s, flag %s and filepath %s \n",
!test.match, test.pattern, test.flagName, test.filePath)
}
}
}
}
+6
View File
@@ -51,6 +51,9 @@ type contentMessage struct {
VersionIndex int `json:"versionIndex,omitempty"`
IsDeleteMarker bool `json:"isDeleteMarker,omitempty"`
StorageClass string `json:"storageClass,omitempty"`
Metadata map[string]string `json:"metadata,omitempty"`
Tags map[string]string `json:"tags,omitempty"`
}
// String colorized string message.
@@ -137,6 +140,9 @@ func generateContentMessages(clntURL ClientURL, ctnts []*ClientContent, printAll
contentMsg.Size = c.Size
contentMsg.StorageClass = c.StorageClass
contentMsg.Metadata = c.Metadata
contentMsg.Tags = c.Tags
md5sum := strings.TrimPrefix(c.ETag, "\"")
md5sum = strings.TrimSuffix(md5sum, "\"")
contentMsg.ETag = md5sum
+2
View File
@@ -125,3 +125,5 @@ require (
google.golang.org/protobuf v1.28.1 // indirect
gopkg.in/ini.v1 v1.67.0 // indirect
)
replace github.com/minio/minio-go/v7 => github.com/klauspost/minio-go/v7 v7.0.0-20230330164821-4ec9eb28c34e
+3 -7
View File
@@ -436,15 +436,15 @@ github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7V
github.com/julienschmidt/httprouter v1.3.0/go.mod h1:JR6WtHb+2LUe8TCKY3cZOxFyyO8IZAc4RVcycCCAKdM=
github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8=
github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
github.com/klauspost/compress v1.15.9/go.mod h1:PhcZ0MbTNciWF3rruxRgKxI5NkcHHrHUDtV4Yw2GlzU=
github.com/klauspost/compress v1.16.0 h1:iULayQNOReoYUe+1qtKOqw9CwJv3aNQu8ivo7lw1HU4=
github.com/klauspost/compress v1.16.0/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE=
github.com/klauspost/cpuid/v2 v2.0.1/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
github.com/klauspost/cpuid/v2 v2.0.4/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
github.com/klauspost/cpuid/v2 v2.1.0/go.mod h1:RVVoqg1df56z8g3pUjL/3lE5UfnlrJX8tyFgg4nqhuY=
github.com/klauspost/cpuid/v2 v2.1.2/go.mod h1:RVVoqg1df56z8g3pUjL/3lE5UfnlrJX8tyFgg4nqhuY=
github.com/klauspost/cpuid/v2 v2.2.4 h1:acbojRNwl3o09bUq+yDCtZFc1aiwaAAxtcn8YkZXnvk=
github.com/klauspost/cpuid/v2 v2.2.4/go.mod h1:RVVoqg1df56z8g3pUjL/3lE5UfnlrJX8tyFgg4nqhuY=
github.com/klauspost/minio-go/v7 v7.0.0-20230330164821-4ec9eb28c34e h1:tczqly/cEYA2+z+YaDdoUrXwS6ZQNNbXC3GXlIBTbpI=
github.com/klauspost/minio-go/v7 v7.0.0-20230330164821-4ec9eb28c34e/go.mod h1:IbbodHyjUAguneyucUaahv+VMNs/EOTV9du7A7/Z3HU=
github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
github.com/konsorten/go-windows-terminal-sequences v1.0.3/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
github.com/kr/fs v0.1.0/go.mod h1:FFnZGqtBN9Gxj7eW1uZ42v5BccTP0vu6NEaFoC2HwRg=
@@ -519,9 +519,6 @@ github.com/minio/madmin-go/v2 v2.0.18 h1:5kME44CIL7RlNm99hg6EU0K5AiIX0RtVHFu0nME
github.com/minio/madmin-go/v2 v2.0.18/go.mod h1:8bL1RMNkblIENFSgGYjeHrzUx9PxROb7OqfNuMU9ivE=
github.com/minio/md5-simd v1.1.2 h1:Gdi1DZK69+ZVMoNHRXJyNcxrMA4dSxoYHZSQbirFg34=
github.com/minio/md5-simd v1.1.2/go.mod h1:MzdKDxYpY2BT9XQFocsiZf/NKVtR7nkE4RoEpN+20RM=
github.com/minio/minio-go/v7 v7.0.41/go.mod h1:nCrRzjoSUQh8hgKKtu3Y708OLvRLtuASMg2/nvmbarw=
github.com/minio/minio-go/v7 v7.0.49 h1:dE5DfOtnXMXCjr/HWI6zN9vCrY6Sv666qhhiwUMvGV4=
github.com/minio/minio-go/v7 v7.0.49/go.mod h1:UI34MvQEiob3Cf/gGExGMmzugkM/tNgbFypNDy5LMVc=
github.com/minio/mux v1.9.0 h1:dWafQFyEfGhJvK6AwLOt83bIG5bxKxKJnKMCi0XAaoA=
github.com/minio/mux v1.9.0/go.mod h1:1pAare17ZRL5GpmNL+9YmqHoWnLmMZF9C/ioUCfy0BQ=
github.com/minio/pkg v1.5.4/go.mod h1:2MOaRFdmFKULD+uOLc3qHLGTQTuxCNPKNPfLBTxC8CA=
@@ -761,7 +758,6 @@ golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5y
golang.org/x/crypto v0.0.0-20211209193657-4570a0811e8b/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
golang.org/x/crypto v0.0.0-20220427172511-eb4f295cb31f/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
golang.org/x/crypto v0.0.0-20220722155217-630584e8d5aa/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
golang.org/x/crypto v0.0.0-20221012134737-56aed061732a/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
golang.org/x/crypto v0.6.0 h1:qfktjS5LUO+fFKeJXZ+ikTRijMmljikvG68fpMMruSc=
golang.org/x/crypto v0.6.0/go.mod h1:OFC/31mSvZgRz0V1QTNCzfAI1aIRzbiufJtkMIlEp58=
@@ -855,6 +851,7 @@ golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug
golang.org/x/net v0.0.0-20220909164309-bea034e7d591/go.mod h1:YDH+HFinaLZZlnHAfSS6ZXJJ9M9t4Dl22yv3iI2vPwk=
golang.org/x/net v0.0.0-20221017152216-f25eb7ecb193/go.mod h1:RpDiru2p0u2F0lLpEoqnP2+7xs0ifAuOcJ442g6GU2s=
golang.org/x/net v0.3.0/go.mod h1:MBQ8lrhLObU/6UmLb4fmbmk5OcyYmqtbGd/9yIeKjEE=
golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
golang.org/x/net v0.7.0 h1:rJrUqqhjsgNp7KqAIc25s9pZnjU7TUcSY7HcVZjdn1g=
golang.org/x/net v0.7.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
@@ -1298,7 +1295,6 @@ gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI=
gopkg.in/h2non/filetype.v1 v1.0.5 h1:CC1jjJjoEhNVbMhXYalmGBhOBK2V70Q1N850wt/98/Y=
gopkg.in/h2non/filetype.v1 v1.0.5/go.mod h1:M0yem4rwSX5lLVrkEuRRp2/NinFMD5vgJ4DlAhZcfNo=
gopkg.in/ini.v1 v1.62.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k=
gopkg.in/ini.v1 v1.66.6/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k=
gopkg.in/ini.v1 v1.67.0 h1:Dgnx+6+nfE+IfzjUEISNeydPJh9AXNNsWbGP9KzCsOA=
gopkg.in/ini.v1 v1.67.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k=
gopkg.in/urfave/cli.v1 v1.20.0/go.mod h1:vuBzUtMdQeixQj8LVd+/98pzhxNGQoyuPBlsXHOQNO0=