diff --git a/cmd/ilm-add.go b/cmd/ilm-add.go index 6fde7949..15ce7c53 100644 --- a/cmd/ilm-add.go +++ b/cmd/ilm-add.go @@ -23,7 +23,7 @@ import ( "github.com/minio/mc/cmd/ilm" json "github.com/minio/mc/pkg/colorjson" "github.com/minio/mc/pkg/probe" - minio "github.com/minio/minio-go/v7" + "github.com/minio/minio-go/v7" "github.com/minio/minio-go/v7/pkg/lifecycle" "github.com/minio/minio/pkg/console" ) @@ -44,43 +44,30 @@ FLAGS: {{range .VisibleFlags}}{{.}} {{end}} DESCRIPTION: - Add a rule to the existing set of lifecycle configuration rules, - If a rule with ID already exists it is replaced with the new rule. + Add a lifecycle configuration rule. EXAMPLES: - 1. Add rule for testbucket on s3. Both expiry & transition are entered as dates. - {{.Prompt}} {{.HelpName}} --id "Devices" --prefix "dev/" \ - --expiry-date "2020-09-17" --transition-date "2020-05-01" \ - --storage-class "GLACIER" s3/testbucket + 1. Add expiration rule on mybucket. + {{.Prompt}} {{.HelpName}} --expiry-days "200" myminio/mybucket - 2. Add rule for testbucket on s3. Both expiry and transition are number of days. - {{.Prompt}} {{.HelpName}} --id "Docs" --prefix "doc/" \ - --expiry-days "300" --transition-days "200" \ - --storage-class "GLACIER" s3/testbucket + 2. Add expiry and transition date rules on a prefix in mybucket. + {{.Prompt}} {{.HelpName}} -expiry-date "2025-09-17" --transition-date "2025-05-01" \ + --storage-class "GLACIER" myminio/mybucket/doc - 3. Add rule for testbucket on s3. Only expiry is given as number of days and transition is not set. - {{.Prompt}} {{.HelpName}} --id "Docs" --prefix "doc/" \ - --expiry-days "200" \ - --tags "docformat=docx&plaintextformat=txt&exportFormat=pdf" s3/testbucket + 3. Add expiry and transition days rules on a prefix in mybucket. + {{.Prompt}} {{.HelpName}} -expiry-days "300" --transition-days "200" \ + --storage-class "GLACIER" myminio/mybucket/doc `, } var ilmAddFlags = []cli.Flag{ - cli.StringFlag{ - Name: "id", - Usage: "id for the rule, should be a unique value", - }, - cli.StringFlag{ - Name: "prefix", - Usage: "prefix to apply the lifecycle configuration rule", - }, cli.StringFlag{ Name: "tags", Usage: "format '=&=&=', multiple values allowed for multiple key/value pairs", }, cli.StringFlag{ Name: "expiry-date", - Usage: "format 'YYYY-mm-dd' the date of expiration", + Usage: "format 'YYYY-MM-DD' the date of expiration", }, cli.StringFlag{ Name: "expiry-days", @@ -125,11 +112,6 @@ func checkILMAddSyntax(ctx *cli.Context) { if len(ctx.Args()) != 1 { cli.ShowCommandHelpAndExit(ctx, "add", globalErrorExitStatus) } - - id := ctx.String("id") - if id == "" { - fatalIf(errInvalidArgument(), "ID for lifecycle rule cannot be empty, please refer mc "+ctx.Command.FullName()+" --help for more details") - } } // Calls SetBucketLifecycle with the XML representation of lifecycleConfiguration type. @@ -155,17 +137,16 @@ func mainILMAdd(cliCtx *cli.Context) error { } } - // Configuration that needs to be set is returned by ilm.GetILMConfigToSet. - // A new rule is added or the rule (if existing) is replaced - lfcCfg, err = ilm.ApplyNewILMConfig(cliCtx, lfcCfg) - fatalIf(err.Trace(args...), "Unable to generate new lifecyle rules for the input") + opts := ilm.GetLifecycleOptions(cliCtx) + lfcCfg, err = opts.ToConfig(lfcCfg) + fatalIf(err.Trace(args...), "Unable to generate new lifecycle rules for the input") fatalIf(client.SetLifecycle(ctx, lfcCfg).Trace(urlStr), "Unable to set new lifecycle rules") printMsg(ilmAddMessage{ Status: "success", Target: urlStr, - ID: cliCtx.String("id"), + ID: opts.ID, }) return nil diff --git a/cmd/ilm-export.go b/cmd/ilm-export.go index b33548d7..0fe57b00 100644 --- a/cmd/ilm-export.go +++ b/cmd/ilm-export.go @@ -42,11 +42,11 @@ DESCRIPTION: Exports lifecycle configuration in JSON format to STDOUT. EXAMPLES: - 1. Export lifecycle configuration for 'testbucket' to 'lifecycle.json' file. - {{.Prompt}} {{.HelpName}} myminio/testbucket > lifecycle.json + 1. Export lifecycle configuration for 'mybucket' to 'lifecycle.json' file. + {{.Prompt}} {{.HelpName}} myminio/mybucket > lifecycle.json - 2. Print lifecycle configuration for 'testbucket' to STDOUT. - {{.Prompt}} {{.HelpName}} play/testbucket + 2. Print lifecycle configuration for 'mybucket' to STDOUT. + {{.Prompt}} {{.HelpName}} play/mybucket `, } diff --git a/cmd/ilm-import.go b/cmd/ilm-import.go index 6a6eecd1..291947f9 100644 --- a/cmd/ilm-import.go +++ b/cmd/ilm-import.go @@ -43,11 +43,11 @@ DESCRIPTION: Import entire lifecycle configuration from STDIN, input file is expected to be in JSON format. EXAMPLES: - 1. Set lifecycle configuration for the testbucket on alias 'myminio' to the rules imported from lifecycle.json - {{.Prompt}} {{.HelpName}} myminio/testbucket < lifecycle.json + 1. Set lifecycle configuration for the mybucket on alias 'myminio' to the rules imported from lifecycle.json + {{.Prompt}} {{.HelpName}} myminio/mybucket < lifecycle.json - 2. Set lifecycle configuration for the testbucket on alias 'myminio'. User is expected to enter the JSON contents on STDIN - {{.Prompt}} {{.HelpName}} myminio/testbucket + 2. Set lifecycle configuration for the mybucket on alias 'myminio'. User is expected to enter the JSON contents on STDIN + {{.Prompt}} {{.HelpName}} myminio/mybucket `, } diff --git a/cmd/ilm-list.go b/cmd/ilm-ls.go similarity index 83% rename from cmd/ilm-list.go rename to cmd/ilm-ls.go index 6dcefd46..e2886bd6 100644 --- a/cmd/ilm-list.go +++ b/cmd/ilm-ls.go @@ -40,15 +40,11 @@ var ilmListFlags = []cli.Flag{ Name: "transition", Usage: "display only transition fields", }, - cli.BoolFlag{ - Name: "minimum", - Usage: "display minimum fields such as (id, prefix, status, transition set, expiry set)", - }, } -var ilmListCmd = cli.Command{ - Name: "list", - Usage: "pretty print bucket lifecycle configuration", +var ilmLsCmd = cli.Command{ + Name: "ls", + Usage: "lists lifecycle configuration rules set on a bucket", Action: mainILMList, Before: setGlobalsFromContext, Flags: append(ilmListFlags, globalFlags...), @@ -62,23 +58,20 @@ FLAGS: {{range .VisibleFlags}}{{.}} {{end}} DESCRIPTION: - Pretty prints lifecycle configuration set on a bucket. + List lifecycle configuration rules set on a bucket. EXAMPLES: - 1. List the lifecycle management rules (all fields) for testbucket on alias 'myminio'. - {{.Prompt}} {{.HelpName}} myminio/testbucket + 1. List the lifecycle management rules (all fields) for mybucket on alias 'myminio'. + {{.Prompt}} {{.HelpName}} myminio/mybucket - 2. List the lifecycle management rules (expration date/days fields) for testbucket on alias 'myminio'. - {{.Prompt}} {{.HelpName}} --expiry myminio/testbucket + 2. List the lifecycle management rules (expration date/days fields) for mybucket on alias 'myminio'. + {{.Prompt}} {{.HelpName}} --expiry myminio/mybucket - 3. List the lifecycle management rules (transition date/days, storage class fields) for testbucket on alias 'myminio'. - {{.Prompt}} {{.HelpName}} --transition myminio/testbucket + 3. List the lifecycle management rules (transition date/days, storage class fields) for mybucket on alias 'myminio'. + {{.Prompt}} {{.HelpName}} --transition myminio/mybucket - 4. List the lifecycle management rules (minimum details) for testbucket on alias 'myminio'. - {{.Prompt}} {{.HelpName}} --minimum myminio/testbucket - - 5. List the lifecycle management rules in JSON format for testbucket on alias 'myminio'. - {{.Prompt}} {{.HelpName}} --json myminio/testbucket + 4. List the lifecycle management rules in JSON format for mybucket on alias 'myminio'. + {{.Prompt}} {{.HelpName}} --json myminio/mybucket `, } @@ -92,9 +85,9 @@ type ilmListMessage struct { func (i ilmListMessage) String() string { showExpiry := i.Context.Bool("expiry") showTransition := i.Context.Bool("transition") - showMinimum := i.Context.Bool("minimum") + // If none of the flags are explicitly mentioned, all fields are shown. - showAll := !showExpiry && !showTransition && !showMinimum + showAll := !showExpiry && !showTransition var hdrLabelIndexMap map[string]int var alignedHdrLabels []string @@ -105,7 +98,7 @@ func (i ilmListMessage) String() string { ilm.PopulateILMDataForDisplay(i.Config, &hdrLabelIndexMap, &alignedHdrLabels, &cellDataNoTags, &cellDataWithTags, &tagRows, - showAll, showMinimum, showExpiry, showTransition) + showAll, showExpiry, showTransition) // Entire table content. var tblContents string @@ -149,10 +142,9 @@ func (i ilmListMessage) JSON() string { return string(msgBytes) } -// validateILMListFlagSet - Only one of these flags needs to be set for display: --json, --expiry, --transition, --minimum +// validateILMListFlagSet - Only one of these flags needs to be set for display: --json, --expiry, --transition func validateILMListFlagSet(ctx *cli.Context) bool { - var flags = [...]bool{ctx.Bool("expiry"), ctx.Bool("transition"), ctx.Bool("json"), - ctx.Bool("minimum")} + var flags = [...]bool{ctx.Bool("expiry"), ctx.Bool("transition"), ctx.Bool("json")} found := false for _, flag := range flags { if found && flag { @@ -167,11 +159,11 @@ func validateILMListFlagSet(ctx *cli.Context) bool { // checkILMListSyntax - validate arguments passed by a user func checkILMListSyntax(ctx *cli.Context) { if len(ctx.Args()) != 1 { - cli.ShowCommandHelpAndExit(ctx, "list", globalErrorExitStatus) + cli.ShowCommandHelpAndExit(ctx, "ls", globalErrorExitStatus) } if !validateILMListFlagSet(ctx) { - fatalIf(errInvalidArgument(), "only one display field flag is allowed per list command. Refer mc "+ctx.Command.FullName()+" --help.") + fatalIf(errInvalidArgument(), "only one display field flag is allowed per ls command. Refer mc "+ctx.Command.FullName()+" --help.") } } @@ -273,7 +265,7 @@ func mainILMList(cliCtx *cli.Context) error { if len(ilmCfg.Rules) == 0 { fatalIf(probe.NewError(errors.New("lifecycle configuration not set")).Trace(urlStr), - "Unable to list lifecycle configuration") + "Unable to ls lifecycle configuration") } printMsg(ilmListMessage{ diff --git a/cmd/ilm-main.go b/cmd/ilm-main.go index 0eec58f8..6642d1ef 100644 --- a/cmd/ilm-main.go +++ b/cmd/ilm-main.go @@ -30,9 +30,10 @@ var bucketILMCmd = cli.Command{ Flags: globalFlags, HideHelpCommand: true, Subcommands: []cli.Command{ - ilmListCmd, + ilmLsCmd, ilmAddCmd, - ilmRemoveCmd, + ilmRmCmd, + ilmSetCmd, ilmExportCmd, ilmImportCmd, }, diff --git a/cmd/ilm-remove.go b/cmd/ilm-rm.go similarity index 89% rename from cmd/ilm-remove.go rename to cmd/ilm-rm.go index 0f7f4ba3..dfb24ed6 100644 --- a/cmd/ilm-remove.go +++ b/cmd/ilm-rm.go @@ -41,9 +41,9 @@ var ilmRemoveFlags = []cli.Flag{ }, } -var ilmRemoveCmd = cli.Command{ - Name: "remove", - Usage: "remove (if any) existing lifecycle configuration rule with the id", +var ilmRmCmd = cli.Command{ + Name: "rm", + Usage: "remove (if any) existing lifecycle configuration rule", Action: mainILMRemove, Before: setGlobalsFromContext, Flags: append(ilmRemoveFlags, globalFlags...), @@ -61,12 +61,12 @@ DESCRIPTION: all the lifecycle rules on a bucket with '--all --force' option. EXAMPLES: - 1. Remove the lifecycle management configuration rule given by ID "Documents" for testbucket on alias 'myminio'. ID is case sensitive. - {{.Prompt}} {{.HelpName}} --id "Documents" myminio/testbucket + 1. Remove the lifecycle management configuration rule given by ID "bgrt1ghju" for mybucket on alias 'myminio'. ID is case sensitive. + {{.Prompt}} {{.HelpName}} --id "bgrt1ghju" myminio/mybucket - 2. Remove ALL the lifecycle management configuration rules for testbucket on alias 'myminio'. + 2. Remove ALL the lifecycle management configuration rules for mybucket on alias 'myminio'. Because the result is complete removal, the use of --force flag is enforced. - {{.Prompt}} {{.HelpName}} --all --force myminio/testbucket + {{.Prompt}} {{.HelpName}} --all --force myminio/mybucket `, } @@ -93,7 +93,7 @@ func (i ilmRmMessage) JSON() string { func checkILMRemoveSyntax(ctx *cli.Context) { if len(ctx.Args()) != 1 { - cli.ShowCommandHelpAndExit(ctx, "remove", globalErrorExitStatus) + cli.ShowCommandHelpAndExit(ctx, "rm", globalErrorExitStatus) } ilmAll := ctx.Bool("all") diff --git a/cmd/ilm-set.go b/cmd/ilm-set.go new file mode 100644 index 00000000..63580f41 --- /dev/null +++ b/cmd/ilm-set.go @@ -0,0 +1,161 @@ +/* + * 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 ( + "context" + + "github.com/minio/cli" + "github.com/minio/mc/cmd/ilm" + json "github.com/minio/mc/pkg/colorjson" + "github.com/minio/mc/pkg/probe" + minio "github.com/minio/minio-go/v7" + "github.com/minio/minio-go/v7/pkg/lifecycle" + "github.com/minio/minio/pkg/console" +) + +var ilmSetCmd = cli.Command{ + Name: "set", + Usage: "modify a lifecycle configuration rule with given id", + Action: mainILMSet, + Before: setGlobalsFromContext, + Flags: append(ilmSetFlags, globalFlags...), + CustomHelpTemplate: `NAME: + {{.HelpName}} - {{.Usage}} + +USAGE: + {{.HelpName}} [COMMAND FLAGS] TARGET + +FLAGS: + {{range .VisibleFlags}}{{.}} + {{end}} +DESCRIPTION: + modify a lifecycle configuration rule with given id. + +EXAMPLES: + 1. Modify the expiration date for an existing rule with id "rHTY.a123". + {{.Prompt}} {{.HelpName}} --id "rHTY.a123" \ + --expiry-date "2020-09-17" s3/mybucket + + 2. Modify the expiration and transition days for an existing rule with id "hGHKijqpo123". + {{.Prompt}} {{.HelpName}} --id "hGHKijqpo123" \ + --expiry-days "300" --transition-days "200" \ + --storage-class "GLACIER" s3/mybucket +`, +} + +var ilmSetFlags = []cli.Flag{ + cli.StringFlag{ + Name: "id", + Usage: "id of the rule to be modified", + }, + cli.StringFlag{ + Name: "tags", + Usage: "format '=&=&=', multiple values allowed for multiple key/value pairs", + }, + cli.StringFlag{ + Name: "expiry-date", + Usage: "format 'YYYY-MM-DD' the date of expiration", + }, + cli.StringFlag{ + Name: "expiry-days", + Usage: "the number of days to expiration", + }, + cli.StringFlag{ + Name: "transition-date", + Usage: "format 'YYYY-MM-DD' for the date to transition", + }, + cli.StringFlag{ + Name: "transition-days", + Usage: "the number of days to transition", + }, + cli.StringFlag{ + Name: "storage-class", + Usage: "storage class for transition (STANDARD_IA, ONEZONE_IA, GLACIER. Etc)", + }, + cli.BoolFlag{ + Name: "disable", + Usage: "disable the rule", + }, +} + +type ilmSetMessage struct { + Status string `json:"status"` + Target string `json:"target"` + ID string `json:"id"` +} + +func (i ilmSetMessage) String() string { + return console.Colorize(ilmThemeResultSuccess, "Lifecycle configuration rule added with ID `"+i.ID+"` to "+i.Target+".") +} + +func (i ilmSetMessage) JSON() string { + msgBytes, e := json.MarshalIndent(i, "", " ") + fatalIf(probe.NewError(e), "Unable to marshal into JSON.") + return string(msgBytes) +} + +// Validate user given arguments +func checkILMSetSyntax(ctx *cli.Context) { + if len(ctx.Args()) != 1 { + cli.ShowCommandHelpAndExit(ctx, "set", globalErrorExitStatus) + } + id := ctx.String("id") + if id == "" { + fatalIf(errInvalidArgument(), "ID for lifecycle rule cannot be empty, please refer mc "+ctx.Command.FullName()+" --help for more details") + } +} + +// Calls SetBucketLifecycle with the XML representation of lifecycleConfiguration type. +func mainILMSet(cliCtx *cli.Context) error { + ctx, cancelILMSet := context.WithCancel(globalContext) + defer cancelILMSet() + + checkILMSetSyntax(cliCtx) + setILMDisplayColorScheme() + args := cliCtx.Args() + urlStr := args.Get(0) + + client, err := newClient(urlStr) + fatalIf(err.Trace(urlStr), "Unable to initialize client for "+urlStr) + + // Configuration that is already set. + lfcCfg, err := client.GetLifecycle(ctx) + if err != nil { + if e := err.ToGoError(); minio.ToErrorResponse(e).Code == "NoSuchLifecycleConfiguration" { + lfcCfg = lifecycle.NewConfiguration() + } else { + fatalIf(err.Trace(args...), "Unable to fetch lifecycle rules for "+urlStr) + } + } + + // Configuration that needs to be set is returned by ilm.GetILMConfigToSet. + // A new rule is added or the rule (if existing) is replaced + opts := ilm.GetLifecycleOptions(cliCtx) + lfcCfg, err = opts.ToConfig(lfcCfg) + fatalIf(err.Trace(args...), "Unable to generate new lifecycle rules for the input") + + fatalIf(client.SetLifecycle(ctx, lfcCfg).Trace(urlStr), "Unable to set new lifecycle rules") + + printMsg(ilmSetMessage{ + Status: "success", + Target: urlStr, + ID: opts.ID, + }) + + return nil +} diff --git a/cmd/ilm/options.go b/cmd/ilm/options.go index 78fb49b7..cc95f5dd 100644 --- a/cmd/ilm/options.go +++ b/cmd/ilm/options.go @@ -24,6 +24,7 @@ import ( "github.com/minio/cli" "github.com/minio/mc/pkg/probe" "github.com/minio/minio-go/v7/pkg/lifecycle" + "github.com/rs/xid" ) const defaultILMDateFormat string = "2006-01-02" @@ -97,19 +98,23 @@ func RemoveILMRule(lfcCfg *lifecycle.Configuration, ilmID string) (*lifecycle.Co return lfcCfg, nil } -type lifecycleOptions struct { - ID string - Prefix string - Status bool - Tags string - ExpiryDate string - ExpiryDays string - TransitionDate string - TransitionDays string - StorageClass string +// LifecycleOptions is structure to encapsulate +type LifecycleOptions struct { + ID string + Prefix string + Status bool + IsTagsSet bool + IsStorageClassSet bool + Tags string + ExpiryDate string + ExpiryDays string + TransitionDate string + TransitionDays string + StorageClass string } -func (opts lifecycleOptions) ToConfig(config *lifecycle.Configuration) (*lifecycle.Configuration, *probe.Error) { +// ToConfig create lifecycle.Configuration based on LifecycleOptions +func (opts LifecycleOptions) ToConfig(config *lifecycle.Configuration) (*lifecycle.Configuration, *probe.Error) { expiry, err := parseExpiry(opts.ExpiryDate, opts.ExpiryDays) if err != nil { return nil, err.Trace(opts.ExpiryDate, opts.ExpiryDays) @@ -144,16 +149,15 @@ func (opts lifecycleOptions) ToConfig(config *lifecycle.Configuration) (*lifecyc Transition: transition, } - if err := validateILMRule(newRule); err != nil { - return nil, err.Trace(opts.ID) - } - ruleFound := false for i, rule := range config.Rules { if rule.ID != newRule.ID { continue } - config.Rules[i] = newRule + config.Rules[i] = applyRuleFields(newRule, config.Rules[i], opts) + if err := validateILMRule(config.Rules[i]); err != nil { + return nil, err.Trace(opts.ID) + } ruleFound = true break } @@ -165,23 +169,94 @@ func (opts lifecycleOptions) ToConfig(config *lifecycle.Configuration) (*lifecyc return config, nil } -func getLifecycleOptions(ctx *cli.Context) lifecycleOptions { - return lifecycleOptions{ - ID: ctx.String("id"), - Prefix: ctx.String("prefix"), - Status: !ctx.Bool("disable"), - Tags: ctx.String("tags"), - ExpiryDate: ctx.String("expiry-date"), - ExpiryDays: ctx.String("expiry-days"), - TransitionDate: ctx.String("transition-date"), - TransitionDays: ctx.String("transition-days"), - StorageClass: ctx.String("storage-class"), +// GetLifecycleOptions create LifeCycleOptions based on cli inputs +func GetLifecycleOptions(ctx *cli.Context) LifecycleOptions { + var id string = ctx.String("id") + if id == "" { + id = xid.New().String() + } + // split the first arg i.e. path into alias, bucket and prefix + result := strings.SplitN(ctx.Args().First(), "/", 3) + // get the prefix from path + var prefix string + if len(result) > 2 { + prefix = result[len(result)-1] + } + return LifecycleOptions{ + ID: id, + Prefix: prefix, + Status: !ctx.Bool("disable"), + IsTagsSet: ctx.IsSet("tags"), + IsStorageClassSet: ctx.IsSet("storage-class"), + Tags: ctx.String("tags"), + ExpiryDate: ctx.String("expiry-date"), + ExpiryDays: ctx.String("expiry-days"), + TransitionDate: ctx.String("transition-date"), + TransitionDays: ctx.String("transition-days"), + StorageClass: ctx.String("storage-class"), } } -// ApplyNewILMConfig apply new lifecycle rules to existing lifecycle configuration, this -// function returns modified/overwritten rules if any. -func ApplyNewILMConfig(ctx *cli.Context, config *lifecycle.Configuration) (*lifecycle.Configuration, *probe.Error) { - opts := getLifecycleOptions(ctx) - return opts.ToConfig(config) +// Applies non empty fields from src to dest Rule and return the dest Rule +func applyRuleFields(src lifecycle.Rule, dest lifecycle.Rule, opts LifecycleOptions) lifecycle.Rule { + // since prefix is a part of command args, it is always present in the src rule and + // it should be always set to the destination. + dest.RuleFilter.Prefix = src.RuleFilter.Prefix + + // If src has tags, it should override the destination + if len(src.RuleFilter.And.Tags) > 0 { + dest.RuleFilter.And.Tags = src.RuleFilter.And.Tags + dest.RuleFilter.And.Prefix = src.RuleFilter.And.Prefix + dest.RuleFilter.Prefix = "" + } + + if src.RuleFilter.And.Tags == nil { + if opts.IsTagsSet { + // If src tags is empty and isTagFlagSet then user provided the --tag flag with "" value + // dest tags should be deleted + dest.RuleFilter.And.Tags = []lifecycle.Tag{} + dest.RuleFilter.And.Prefix = "" + dest.RuleFilter.Prefix = src.RuleFilter.Prefix + } else { + if dest.RuleFilter.And.Tags != nil { + // Update prefixes only + dest.RuleFilter.And.Prefix = src.RuleFilter.Prefix + dest.RuleFilter.Prefix = "" + } else { + dest.RuleFilter.Prefix = src.RuleFilter.Prefix + dest.RuleFilter.And.Prefix = "" + } + } + } + + // only one of expiration day, date or transition day, date is expected + if !src.Expiration.IsDateNull() { + dest.Expiration.Date = src.Expiration.Date + // reset everything else + dest.Expiration.Days = 0 + } else if !src.Expiration.IsDaysNull() { + dest.Expiration.Days = src.Expiration.Days + // reset everything else + dest.Expiration.Date = lifecycle.ExpirationDate{} + } + + if !src.Transition.IsDateNull() { + dest.Transition.Date = src.Transition.Date + // reset everything else + dest.Transition.Days = 0 + } else if !src.Transition.IsDaysNull() { + dest.Transition.Days = src.Transition.Days + // reset everything else + dest.Transition.Date = lifecycle.ExpirationDate{} + } + + if opts.IsStorageClassSet { + dest.Transition.StorageClass = src.Transition.StorageClass + } + + // Updated the status + if src.Status != "" { + dest.Status = src.Status + } + return dest } diff --git a/cmd/ilm/parse.go b/cmd/ilm/parse.go index 1313d851..5ec7a23c 100644 --- a/cmd/ilm/parse.go +++ b/cmd/ilm/parse.go @@ -51,8 +51,8 @@ func extractILMTags(tagLabelVal string) []lifecycle.Tag { // For example: Transition has to happen before Expiry. // Storage class must be specified if transition date/days is provided. func validateTranExpDate(rule lifecycle.Rule) error { - expiryDateSet := rule.Expiration.IsDateNull() - expiryDaySet := rule.Expiration.IsDaysNull() + expiryDateSet := !rule.Expiration.IsDateNull() + expiryDaySet := !rule.Expiration.IsDaysNull() transitionSet := !rule.Transition.IsNull() transitionDateSet := transitionSet && !rule.Transition.IsDateNull() @@ -68,6 +68,12 @@ func validateTranExpDate(rule lifecycle.Rule) error { return errors.New(errMsg) } } + if transitionDateSet && rule.Transition.StorageClass == "" { + return errors.New("if storage class is set a valid transitionDate or transitionDay must be set") + } + if transitionDaySet && rule.Transition.StorageClass == "" { + return errors.New("if storage class is set a valid transitionDate or transitionDay must be set") + } return nil } @@ -132,25 +138,20 @@ func validateILMRule(rule lifecycle.Rule) *probe.Error { // Returns valid lifecycleTransition to be included in lifecycleRule func parseTransition(storageClass, transitionDateStr, transitionDayStr string) (transition lifecycle.Transition, err *probe.Error) { storageClass = strings.ToUpper(storageClass) // Just-in-case the user has entered lower case characters. - if storageClass != "" { - if transitionDateStr != "" { - transitionDate, e := time.Parse(defaultILMDateFormat, transitionDateStr) - if e != nil { - return lifecycle.Transition{}, probe.NewError(e) - } - transition.Date = lifecycle.ExpirationDate{Time: transitionDate} - } else if transitionDayStr != "" { - transitionDay, e := strconv.Atoi(transitionDayStr) - if e != nil { - return lifecycle.Transition{}, probe.NewError(e) - } - transition.Days = lifecycle.ExpirationDays(transitionDay) - } else { - return lifecycle.Transition{}, probe.NewError(errors.New("if storage class is set a valid transitionDate or transitionDay must be set")) + if transitionDateStr != "" { + transitionDate, e := time.Parse(defaultILMDateFormat, transitionDateStr) + if e != nil { + return lifecycle.Transition{}, probe.NewError(e) } - transition.StorageClass = storageClass + transition.Date = lifecycle.ExpirationDate{Time: transitionDate} + } else if transitionDayStr != "" { + transitionDay, e := strconv.Atoi(transitionDayStr) + if e != nil { + return lifecycle.Transition{}, probe.NewError(e) + } + transition.Days = lifecycle.ExpirationDays(transitionDay) } - + transition.StorageClass = storageClass return transition, nil } diff --git a/cmd/ilm/tabular_info.go b/cmd/ilm/tabular_info.go index 1798378a..76af0bc4 100644 --- a/cmd/ilm/tabular_info.go +++ b/cmd/ilm/tabular_info.go @@ -24,7 +24,7 @@ import ( const ( // rule ID field column width in table output - idColumnWidth int = 16 + idColumnWidth int = 22 // rule prefix field column width in table output prefixColumnWidth int = 16 // StatusColumnWidth column width in table output @@ -34,7 +34,7 @@ const ( // ExpiryDatesColumnWidth column width in table output expiryDatesColumnWidth int = 14 // TagsColumnWidth column width in table output - tagsColumnWidth int = 18 + tagsColumnWidth int = 24 // TransitionColumnWidth column width in table output transitionColumnWidth int = 14 // TransitionDateColumnWidth column width in table output @@ -97,14 +97,13 @@ type showDetails struct { allAvailable bool expiry bool transition bool - minimum bool } // PopulateILMDataForDisplay based on showDetails determined by user input, populate the ILM display // table with information. Table is constructed row-by-row. Headers are first, then the rest of the rows. func PopulateILMDataForDisplay(ilmCfg *lifecycle.Configuration, rowCheck *map[string]int, alignedHdrLabels *[]string, cellDataNoTags *[][]string, cellDataWithTags *[][]string, tagRows *map[string][]string, - showAll, showMin, showExpiry, showTransition bool) { + showAll, showExpiry, showTransition bool) { // We need the different column headers and their respective column index // where they appear in a map data-structure format. @@ -114,7 +113,6 @@ func PopulateILMDataForDisplay(ilmCfg *lifecycle.Configuration, rowCheck *map[st *tagRows = make(map[string][]string) showOpts := showDetails{ allAvailable: showAll, - minimum: showMin, expiry: showExpiry, transition: showTransition, } @@ -160,9 +158,6 @@ func getILMColumnWidthTable() map[string]int { func checkAddTableCellRows(rowArr *[]string, rowCheck map[string]int, showOpts showDetails, cellInfo tableCellInfo, ruleID string, newRows map[string][]string) { var cellLabel string - if showOpts.minimum { - return - } multLth := len(cellInfo.multLabels) if cellInfo.label != "" || multLth == 0 { if colIdx, ok := rowCheck[cellInfo.labelKey]; ok { @@ -237,7 +232,8 @@ func getExpiryDateVal(rule lifecycle.Rule) string { func getTransitionTick(rule lifecycle.Rule) string { transitionSet := !rule.Transition.IsNull() transitionDateSet := transitionSet && !rule.Transition.IsDateNull() - if !transitionSet || !transitionDateSet { + transitionDaysSet := transitionSet && !rule.Transition.IsDaysNull() + if !transitionSet && !transitionDateSet && !transitionDaysSet { return crossTickCell } return tickCell @@ -408,11 +404,11 @@ func showExpiryDetails(rule lifecycle.Rule, showOpts showDetails) bool { } func showExpTick(showOpts showDetails) bool { - return showOpts.allAvailable || showOpts.minimum + return showOpts.allAvailable } func showTransitionTick(showOpts showDetails) bool { - return (showOpts.allAvailable || showOpts.minimum) + return showOpts.allAvailable } func showTransitionDetails(rule lifecycle.Rule, showOpts showDetails) bool { @@ -425,9 +421,6 @@ func showTransitionDetails(rule lifecycle.Rule, showOpts showDetails) bool { } func showTags(rule lifecycle.Rule, showOpts showDetails) bool { - if showOpts.minimum { - return false - } tagSet := showOpts.allAvailable || !rule.RuleFilter.And.IsEmpty() return tagSet } diff --git a/go.mod b/go.mod index bb63fa6b..321d5ba2 100644 --- a/go.mod +++ b/go.mod @@ -9,6 +9,7 @@ require ( github.com/fatih/color v1.7.0 github.com/inconshreveable/go-update v0.0.0-20160112193335-8152e7eb6ccf github.com/klauspost/compress v1.10.3 + github.com/lithammer/shortuuid v3.0.0+incompatible github.com/mattn/go-ieproxy v0.0.1 github.com/mattn/go-isatty v0.0.8 github.com/minio/cli v1.22.0 @@ -21,6 +22,7 @@ require ( github.com/pkg/xattr v0.4.1 github.com/posener/complete v1.2.3 github.com/rjeczalik/notify v0.9.2 + github.com/rs/xid v1.2.1 golang.org/x/crypto v0.0.0-20200728195943-123391ffb6de golang.org/x/net v0.0.0-20200707034311-ab3426394381 golang.org/x/sys v0.0.0-20200806125547-5acd03effb82 // indirect diff --git a/go.sum b/go.sum index 3c551427..aabea25e 100644 --- a/go.sum +++ b/go.sum @@ -251,6 +251,9 @@ github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/lib/pq v1.7.0 h1:h93mCPfUSkaul3Ka/VG8uZdmW1uMHDGxzu0NWHuJmHY= github.com/lib/pq v1.7.0/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= +github.com/lithammer/shortuuid v1.0.0 h1:kdcbvjGVEgqeVeDIRtnANOi/F6ftbKrtbxY+cjQmK1Q= +github.com/lithammer/shortuuid v3.0.0+incompatible h1:NcD0xWW/MZYXEHa6ITy6kaXN5nwm/V115vj2YXfhS0w= +github.com/lithammer/shortuuid v3.0.0+incompatible/go.mod h1:FR74pbAuElzOUuenUHTK2Tciko1/vKuIKS9dSkDrA4w= github.com/mailru/easyjson v0.0.0-20180730094502-03f2033d19d5 h1:0x4qcEHDpruK6ML/m/YSlFUUu0UpRD3I2PHsNCuGnyA= github.com/mailru/easyjson v0.0.0-20180730094502-03f2033d19d5/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc= github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU=