diff --git a/cmd/ilm-add.go b/cmd/ilm-add.go index 0c2f0eba..1c6d87ff 100644 --- a/cmd/ilm-add.go +++ b/cmd/ilm-add.go @@ -50,7 +50,7 @@ DESCRIPTION: EXAMPLES: 1. Add a lifecycle rule with an expiration action for all objects in mybucket. - {{.Prompt}} {{.HelpName}} --expiry-days "200" myminio/mybucket + {{.Prompt}} {{.HelpName}} --expire-days "200" myminio/mybucket 2. Add a lifecycle rule with a transition and a noncurrent version transition action for objects with prefix doc/ in mybucket. Tiers must exist in MinIO. Use existing tiers or add new tiers. @@ -60,12 +60,12 @@ EXAMPLES: {{.Prompt}} mc tier add minio myminio MINIOTIER-2 --endpoint https://warm-minio-2.com \ --access-key ACCESSKEY --secret-key SECRETKEY --bucket bucket2 --prefix prefix2 - {{.Prompt}} {{.HelpName}} --prefix "doc/" --transition-days "90" --tier "MINIOTIER-1" \ - --noncurrentversion-transition-days "45" --noncurrentversion-tier "MINIOTIER-2" \ + {{.Prompt}} {{.HelpName}} --prefix "doc/" --transition-days "90" --transition-tier "MINIOTIER-1" \ + --noncurrent-transition-days "45" --noncurrent-transition-tier "MINIOTIER-2" \ myminio/mybucket/ 3. Add a lifecycle rule with an expiration and a noncurrent version expiration action for all objects with prefix doc/ in mybucket. - {{.Prompt}} {{.HelpName}} --prefix "doc/" --expiry-days "300" --noncurrentversion-expiration-days "100" \ + {{.Prompt}} {{.HelpName}} --prefix "doc/" --expire-days "300" --noncurrent-expire-days "100" \ myminio/mybucket/ `, } @@ -73,11 +73,11 @@ EXAMPLES: var ilmAddFlags = []cli.Flag{ cli.StringFlag{ Name: "prefix", - Usage: "specify the prefix", + Usage: "object prefix", }, cli.StringFlag{ Name: "tags", - Usage: "format '=&=&=', multiple values allowed for multiple key/value pairs", + Usage: "key value pairs of the form '=&=&='", }, cli.StringFlag{ Name: "expiry-date", @@ -85,8 +85,22 @@ var ilmAddFlags = []cli.Flag{ Hidden: true, }, cli.StringFlag{ - Name: "expiry-days", - Usage: "the number of days to expiration", + Name: "expiry-days", + Usage: "the number of days to expiration", + Hidden: true, + }, + cli.StringFlag{ + Name: "expire-days", + Usage: "number of days to expire", + }, + cli.BoolFlag{ + Name: "expired-object-delete-marker", + Usage: "remove delete markers with no parallel versions", + Hidden: true, + }, + cli.BoolFlag{ + Name: "expire-delete-marker", + Usage: "expire zombie delete markers", }, cli.StringFlag{ Name: "transition-date", @@ -95,7 +109,7 @@ var ilmAddFlags = []cli.Flag{ }, cli.StringFlag{ Name: "transition-days", - Usage: "the number of days to transition", + Usage: "number of days to transition", }, cli.StringFlag{ Name: "storage-class", @@ -103,28 +117,49 @@ var ilmAddFlags = []cli.Flag{ Hidden: true, }, cli.StringFlag{ - Name: "tier", - Usage: "remote tier where current versions transition to", + Name: "tier", + Usage: "remote tier where current versions transition to", + Hidden: true, }, - cli.BoolFlag{ - Name: "expired-object-delete-marker", - Usage: "remove delete markers with no parallel versions", + cli.StringFlag{ + Name: "transition-tier", + Usage: "remote tier name to transition", }, cli.IntFlag{ - Name: "noncurrentversion-expiration-days", - Usage: "the number of days to remove noncurrent versions", + Name: "noncurrentversion-expiration-days", + Usage: "the number of days to remove noncurrent versions", + Hidden: true, + }, + cli.StringFlag{ + Name: "noncurrent-expire-days", + Usage: "number of days to expire noncurrent versions", }, cli.IntFlag{ - Name: "newer-noncurrentversions-expiration", - Usage: "the number of noncurrent versions to retain", + Name: "newer-noncurrentversions-expiration", + Usage: "the number of noncurrent versions to retain", + Hidden: true, }, cli.IntFlag{ - Name: "noncurrentversion-transition-days", - Usage: "the number of days to transition noncurrent versions", + Name: "noncurrent-expire-newer", + Usage: "number of newer noncurrent versions to retain", }, cli.IntFlag{ - Name: "newer-noncurrentversions-transition", - Usage: "the number of noncurrent versions to retain. If there are this many more recent noncurrent versions they will be transitioned", + Name: "noncurrentversion-transition-days", + Usage: "the number of days to transition noncurrent versions", + Hidden: true, + }, + cli.IntFlag{ + Name: "noncurrent-transition-days", + Usage: "number of days to transition noncurrent versions", + }, + cli.IntFlag{ + Name: "newer-noncurrentversions-transition", + Usage: "the number of noncurrent versions to retain. If there are this many more recent noncurrent versions they will be transitioned", + Hidden: true, + }, + cli.IntFlag{ + Name: "noncurrent-transition-newer", + Usage: "number of noncurrent versions to retain in hot tier", }, cli.StringFlag{ Name: "noncurrentversion-transition-storage-class", @@ -132,8 +167,13 @@ var ilmAddFlags = []cli.Flag{ Hidden: true, }, cli.StringFlag{ - Name: "noncurrentversion-tier", - Usage: "remote tier where noncurrent versions transition to", + Name: "noncurrentversion-tier", + Usage: "remote tier where noncurrent versions transition to", + Hidden: true, + }, + cli.StringFlag{ + Name: "noncurrent-transition-tier", + Usage: "remote tier name to transition", }, } diff --git a/cmd/ilm-ls.go b/cmd/ilm-ls.go index 65c0470c..c09ef29b 100644 --- a/cmd/ilm-ls.go +++ b/cmd/ilm-ls.go @@ -1,4 +1,4 @@ -// Copyright (c) 2015-2021 MinIO, Inc. +// Copyright (c) 2015-2022 MinIO, Inc. // // This file is part of MinIO Object Storage stack // @@ -18,18 +18,17 @@ package cmd import ( - "bytes" "context" "errors" - "strconv" - "strings" + "os" + "github.com/jedib0t/go-pretty/v6/table" + "github.com/jedib0t/go-pretty/v6/text" "github.com/minio/cli" json "github.com/minio/colorjson" "github.com/minio/mc/cmd/ilm" "github.com/minio/mc/pkg/probe" "github.com/minio/minio-go/v7/pkg/lifecycle" - "github.com/minio/pkg/console" ) var ilmListFlags = []cli.Flag{ @@ -85,62 +84,9 @@ type ilmListMessage struct { } func (i ilmListMessage) String() string { - showExpiry := i.Context.Bool("expiry") - showTransition := i.Context.Bool("transition") - - // If none of the flags are explicitly mentioned, all fields are shown. - showAll := !showExpiry && !showTransition - - var hdrLabelIndexMap map[string]int - var alignedHdrLabels []string - var cellDataNoTags [][]string - var cellDataWithTags [][]string - var tagRows map[string][]string - var tbl PrettyTable - - ilm.PopulateILMDataForDisplay(i.Config, &hdrLabelIndexMap, &alignedHdrLabels, - &cellDataNoTags, &cellDataWithTags, &tagRows, - showAll, showExpiry, showTransition) - - // Entire table content. - var tblContents string - - // Fill up fields - var fields []Field - - // The header table - for _, hdr := range alignedHdrLabels { - fields = append(fields, Field{ilmThemeHeader, len(hdr)}) - } - - tbl = newPrettyTable(tableSeperator, fields...) - tblContents = getILMHeader(&tbl, alignedHdrLabels...) - - // If no data to show at all, quit here - if len(cellDataNoTags) == 0 && len(cellDataWithTags) == 0 { - return tblContents - } - - // The data table - var tblRowField *[]string - if len(cellDataNoTags) == 0 { - tblRowField = &cellDataWithTags[0] - } else { - tblRowField = &cellDataNoTags[0] - } - - // Reuse the fields - fields = nil - - for _, hdr := range *tblRowField { - fields = append(fields, Field{ilmThemeRow, len(hdr)}) - } - - tbl = newPrettyTable(tableSeperator, fields...) - tblContents += getILMRowsNoTags(&tbl, &cellDataNoTags) - tblContents += getILMRowsWithTags(&tbl, &cellDataWithTags, tagRows) - - return tblContents + // We don't use this method to display ilm-ls output. This is here to + // implement the interface required by printMsg + return "" } func (i ilmListMessage) JSON() string { @@ -174,86 +120,6 @@ func checkILMListSyntax(ctx *cli.Context) { } } -const tableSeperator = "|" - -func getILMHeader(tbl *PrettyTable, alignedHdrLabels ...string) string { - if len(alignedHdrLabels) == 0 { - return "" - } - row := tbl.buildRow(alignedHdrLabels...) - header := console.Colorize(ilmThemeHeader, row+"\n") - lineRow := buildILMTableLineRow(alignedHdrLabels...) - row = tbl.buildRow(lineRow...) - row = console.Colorize(ilmThemeHeader, row+"\n") - header += row - return header -} - -func buildILMTableLineRow(rowArr ...string) []string { - lineRowArr := make([]string, len(rowArr)) - for index := 0; index < len(rowArr); index++ { - var tagBfr bytes.Buffer - for rowArrChars := 0; rowArrChars < len(rowArr[index]); rowArrChars++ { - tagBfr.WriteByte('-') - } - lineRowArr[index] = tagBfr.String() - } - return lineRowArr -} - -func getILMRowsNoTags(tbl *PrettyTable, cellDataNoTags *[][]string) string { - if cellDataNoTags == nil || len(*cellDataNoTags) == 0 { - return "" - } - var rows string - for _, rowArr := range *cellDataNoTags { - var row string // Table row - // Build & print row - row = tbl.buildRow(rowArr...) - row = console.Colorize(ilmThemeRow, row) - rows += row + "\n" - lineRow := buildILMTableLineRow(rowArr...) - row = tbl.buildRow(lineRow...) - row = console.Colorize(ilmThemeRow, row) - rows += row + "\n" - } - return rows -} - -func getILMRowsWithTags(tbl *PrettyTable, cellDataWithTags *[][]string, newRows map[string][]string) string { - if cellDataWithTags == nil || len(*cellDataWithTags) == 0 { - return "" - } - var rows string - for _, rowArr := range *cellDataWithTags { - if rowArr == nil { - continue - } - var row string // Table row - // Build & print row - row = tbl.buildRow(rowArr...) - row = console.Colorize(ilmThemeRow, row) - rows += row + "\n" - // Add the extra blank rows & tag value in the right column - if len(newRows) > 0 { - for index := 0; index < len(newRows); index++ { - newRow, ok := newRows[strings.TrimSpace(rowArr[0])+strconv.Itoa(index)] - if ok { - row = tbl.buildRow(newRow...) - row = console.Colorize(ilmThemeRow, row) - rows += row + "\n" - } - } - } - // Build & print the line row - lineRow := buildILMTableLineRow(rowArr...) - row = tbl.buildRow(lineRow...) - row = console.Colorize(ilmThemeRow, row) - rows += row + "\n" - } - return rows -} - func mainILMList(cliCtx *cli.Context) error { ctx, cancelILMList := context.WithCancel(globalContext) defer cancelILMList() @@ -264,6 +130,15 @@ func mainILMList(cliCtx *cli.Context) error { args := cliCtx.Args() urlStr := args.Get(0) + // Note: validateILMListFlagsSet ensures we deal with only valid + // combinations here. + var filter ilm.LsFilter + if v := cliCtx.Bool("expiry"); v { + filter = ilm.ExpiryOnly + } + if v := cliCtx.Bool("transition"); v { + filter = ilm.TransitionOnly + } client, err := newClient(urlStr) fatalIf(err.Trace(urlStr), "Unable to initialize client for "+urlStr) @@ -275,12 +150,36 @@ func mainILMList(cliCtx *cli.Context) error { "Unable to ls lifecycle configuration") } - printMsg(ilmListMessage{ - Status: "success", - Target: urlStr, - Context: cliCtx, - Config: ilmCfg, - }) + if globalJSON { + printMsg(ilmListMessage{ + Status: "success", + Target: urlStr, + Context: cliCtx, + Config: ilmCfg, + }) + return nil + } + + for _, tbl := range ilm.ToTables(ilmCfg, filter) { + rows := tbl.Rows() + if len(rows) == 0 { + continue + } + t := table.NewWriter() + t.SetOutputMirror(os.Stdout) + var colCfgs []table.ColumnConfig + for i := 0; i < len(rows[0]); i++ { + colCfgs = append(colCfgs, table.ColumnConfig{ + Align: text.AlignCenter, + }) + } + t.SetColumnConfigs(colCfgs) + t.SetTitle(tbl.Title()) + t.AppendHeader(tbl.ColumnHeaders()) + t.AppendRows(rows) + t.SetStyle(table.StyleLight) + t.Render() + } return nil } diff --git a/cmd/ilm/options.go b/cmd/ilm/options.go index ccb20a06..00fc121f 100644 --- a/cmd/ilm/options.go +++ b/cmd/ilm/options.go @@ -20,7 +20,7 @@ package ilm import ( "errors" "fmt" - "math" + "strconv" "strings" "github.com/minio/cli" @@ -31,51 +31,6 @@ import ( const defaultILMDateFormat string = "2006-01-02" -// Align text in label to center, pad with spaces on either sides. -func getCenterAligned(label string, maxLen int) string { - const toPadWith string = " " - lblLth := len(label) - if lblLth > 1 && lblLth%2 != 0 { - lblLth++ - } else if lblLth == 1 { - lblLth = 2 - } - length := (float64(maxLen - lblLth)) / float64(2) - rptLth := (int)(math.Floor(length / float64(len(toPadWith)))) - leftRptLth := rptLth - rightRptLth := rptLth - if rptLth <= 0 { - leftRptLth = 1 - rightRptLth = 0 - } - output := strings.Repeat(toPadWith, leftRptLth) + label + strings.Repeat(toPadWith, rightRptLth) - return output -} - -// Align text in label to left, pad with spaces. -func getLeftAligned(label string, maxLen int) string { - const toPadWith string = " " - lblLth := len(label) - length := maxLen - lblLth - if length <= 0 { - return label - } - output := strings.Repeat(toPadWith, 1) + label + strings.Repeat(toPadWith, length-1) - return output -} - -// Align text in label to right, pad with spaces. -func getRightAligned(label string, maxLen int) string { - const toPadWith string = " " - lblLth := len(label) - length := maxLen - lblLth - if length <= 0 { - return label - } - output := strings.Repeat(toPadWith, length) + label - return output -} - // RemoveILMRule - Remove the ILM rule (with ilmID) from the configuration in XML that is provided. func RemoveILMRule(lfcCfg *lifecycle.Configuration, ilmID string) (*lifecycle.Configuration, *probe.Error) { if lfcCfg == nil { @@ -287,13 +242,19 @@ func GetLifecycleOptions(ctx *cli.Context) (LifecycleOptions, *probe.Error) { if ctx.IsSet("tier") { tier = strPtr(strings.ToUpper(ctx.String("tier"))) } + if f := "transition-tier"; ctx.IsSet(f) { + tier = strPtr(strings.ToUpper(ctx.String(f))) + } if ctx.IsSet("noncurrentversion-tier") { noncurrentTier = strPtr(strings.ToUpper(ctx.String("noncurrentversion-tier"))) } + if f := "noncurrent-transition-tier"; ctx.IsSet(f) { + noncurrentTier = strPtr(strings.ToUpper(ctx.String(f))) + } if tier != nil && !ctx.IsSet("transition-days") && !ctx.IsSet("transition-date") { return LifecycleOptions{}, probe.NewError(errors.New("transition-date or transition-days must be set")) } - if noncurrentTier != nil && !ctx.IsSet("noncurrentversion-transition-days") { + if noncurrentTier != nil && !ctx.IsSet("noncurrentversion-transition-days") && !ctx.IsSet("noncurrent-transition-days") { return LifecycleOptions{}, probe.NewError(errors.New("noncurrentversion-transition-days must be set")) } // for MinIO transition storage-class is same as label defined on @@ -307,6 +268,9 @@ func GetLifecycleOptions(ctx *cli.Context) (LifecycleOptions, *probe.Error) { if ctx.IsSet("expiry-days") { expiryDays = strPtr(ctx.String("expiry-days")) } + if f := "expire-days"; ctx.IsSet(f) { + expiryDays = strPtr(ctx.String(f)) + } if ctx.IsSet("transition-date") { transitionDate = strPtr(ctx.String("transition-date")) } @@ -316,18 +280,38 @@ func GetLifecycleOptions(ctx *cli.Context) (LifecycleOptions, *probe.Error) { if ctx.IsSet("expired-object-delete-marker") { expiredObjectDeleteMarker = boolPtr(ctx.Bool("expired-object-delete-marker")) } + if f := "expire-delete-marker"; ctx.IsSet(f) { + expiredObjectDeleteMarker = boolPtr(ctx.Bool(f)) + } if ctx.IsSet("noncurrentversion-expiration-days") { noncurrentVersionExpirationDays = intPtr(ctx.Int("noncurrentversion-expiration-days")) } + if f := "noncurrent-expire-days"; ctx.IsSet(f) { + ndaysStr := ctx.String(f) + ndays, err := strconv.Atoi(ndaysStr) + if err != nil { + return LifecycleOptions{}, probe.NewError(fmt.Errorf("failed to parse %s: %v", f, err)) + } + noncurrentVersionExpirationDays = &ndays + } if ctx.IsSet("newer-noncurrentversions-expiration") { newerNoncurrentExpirationVersions = intPtr(ctx.Int("newer-noncurrentversions-expiration")) } + if f := "noncurrent-expire-newer"; ctx.IsSet(f) { + newerNoncurrentExpirationVersions = intPtr(ctx.Int(f)) + } if ctx.IsSet("noncurrentversion-transition-days") { noncurrentVersionTransitionDays = intPtr(ctx.Int("noncurrentversion-transition-days")) } + if f := "noncurrent-transition-days"; ctx.IsSet(f) { + noncurrentVersionTransitionDays = intPtr(ctx.Int(f)) + } if ctx.IsSet("newer-noncurrentversions-transition") { newerNoncurrentTransitionVersions = intPtr(ctx.Int("newer-noncurrentversions-transition")) } + if f := "noncurrent-transition-newer"; ctx.IsSet(f) { + newerNoncurrentTransitionVersions = intPtr(ctx.Int(f)) + } return LifecycleOptions{ ID: id, diff --git a/cmd/ilm/parse.go b/cmd/ilm/parse.go index 9e89b671..191be7ac 100644 --- a/cmd/ilm/parse.go +++ b/cmd/ilm/parse.go @@ -27,6 +27,12 @@ import ( "github.com/minio/minio-go/v7/pkg/lifecycle" ) +// Used in tags. Ex: --tags "key1=value1&key2=value2&key3=value3" +const ( + tagSeperator string = "&" + keyValSeperator string = "=" +) + // Extracts the tags provided by user. The tagfilter array will be put in lifecycleRule structure. func extractILMTags(tagLabelVal string) []lifecycle.Tag { var ilmTagKVList []lifecycle.Tag diff --git a/cmd/ilm/table.go b/cmd/ilm/table.go new file mode 100644 index 00000000..41463fbc --- /dev/null +++ b/cmd/ilm/table.go @@ -0,0 +1,162 @@ +// Copyright (c) 2022 MinIO, Inc. +// +// This file is part of MinIO Object Storage stack +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see . + +package ilm + +import "github.com/jedib0t/go-pretty/v6/table" + +// Table interface provides methods when implemented allows a []T to be rendered +// as a table. +type Table interface { + Title() string + Rows() []table.Row + ColumnHeaders() table.Row +} + +// LsFilter enumerates the 3 possible ilm-ls filter options. +type LsFilter uint8 + +const ( + // None - no filter + None LsFilter = iota + // ExpiryOnly - filter expiration actions across rules + ExpiryOnly + // TransitionOnly - filter transition actions across rules + TransitionOnly +) + +type expirationCurrentRow struct { + ID string + Status string + Prefix string + Tags string + Days int + ExpireDelMarker bool +} + +type expirationCurrentTable []expirationCurrentRow + +func (e expirationCurrentTable) Title() string { + return "Expiration for latest version (Expiration)" +} + +func (e expirationCurrentTable) Rows() (rows []table.Row) { + for _, row := range e { + if row.Prefix == "" { + row.Prefix = "-" + } + if row.Tags == "" { + row.Tags = "-" + } + rows = append(rows, table.Row{row.ID, row.Status, row.Prefix, row.Tags, row.Days, row.ExpireDelMarker}) + } + return rows +} + +func (e expirationCurrentTable) ColumnHeaders() (headers table.Row) { + return table.Row{"ID", "Status", "Prefix", "Tags", "Days to Expire", "Expire DeleteMarker"} +} + +type expirationNoncurrentTable []expirationNoncurrentRow + +type expirationNoncurrentRow struct { + ID string + Status string + Prefix string + Tags string + Days int + KeepVersions int +} + +func (e expirationNoncurrentTable) Title() string { + return "Expiration for older versions (NoncurrentVersionExpiration)" +} + +func (e expirationNoncurrentTable) Rows() (rows []table.Row) { + for _, row := range e { + if row.Prefix == "" { + row.Prefix = "-" + } + if row.Tags == "" { + row.Tags = "-" + } + rows = append(rows, table.Row{row.ID, row.Status, row.Prefix, row.Tags, row.Days, row.KeepVersions}) + } + return rows +} + +func (e expirationNoncurrentTable) ColumnHeaders() (headers table.Row) { + return table.Row{"ID", "Status", "Prefix", "Tags", "Days to Expire", "Keep Versions"} +} + +type tierCurrentTable []tierCurrentRow + +type tierCurrentRow struct { + ID string + Status string + Prefix string + Tags string + Days int + Tier string +} + +func (t tierCurrentTable) Title() string { + return "Transition for latest version (Transition)" +} + +func (t tierCurrentTable) ColumnHeaders() (headers table.Row) { + return table.Row{"ID", "Status", "Prefix", "Tags", "Days to Tier", "Tier"} +} + +func (t tierCurrentTable) Rows() (rows []table.Row) { + for _, row := range t { + if row.Prefix == "" { + row.Prefix = "-" + } + if row.Tags == "" { + row.Tags = "-" + } + rows = append(rows, table.Row{row.ID, row.Status, row.Prefix, row.Tags, row.Days, row.Tier}) + } + return rows +} + +type ( + tierNoncurrentTable []tierNoncurrentRow + tierNoncurrentRow tierCurrentRow +) + +func (t tierNoncurrentTable) Title() string { + return "Transition for older versions (NoncurrentVersionTransition)" +} + +func (t tierNoncurrentTable) ColumnHeaders() table.Row { + return table.Row{"ID", "Status", "Prefix", "Tags", "Days to Tier", "Tier"} +} + +func (t tierNoncurrentTable) Rows() (rows []table.Row) { + for _, row := range t { + if row.Prefix == "" { + row.Prefix = "-" + } + if row.Tags == "" { + row.Tags = "-" + } + rows = append(rows, table.Row{row.ID, row.Status, row.Prefix, row.Tags, row.Days, row.Tier}) + } + return rows +} diff --git a/cmd/ilm/tabular_info.go b/cmd/ilm/tabular_info.go deleted file mode 100644 index ad6f6033..00000000 --- a/cmd/ilm/tabular_info.go +++ /dev/null @@ -1,501 +0,0 @@ -// Copyright (c) 2015-2021 MinIO, Inc. -// -// This file is part of MinIO Object Storage stack -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see . - -package ilm - -import ( - "strconv" - - "github.com/minio/minio-go/v7/pkg/lifecycle" -) - -const ( - // rule ID field column width in table output - idColumnWidth int = 22 - // rule prefix field column width in table output - prefixColumnWidth int = 16 - // StatusColumnWidth column width in table output - statusColumnWidth int = 12 - // IlmDatesColumnWidth column width in table output - ilmDatesColumnWidth int = 14 - // TagsColumnWidth column width in table output - tagsColumnWidth int = 24 - // TypeColumnWidth column width in table output - typeColumnWidth int = 12 - // VersionColumnWidth column width in table output - versionColumnWidth int = 14 - // StorageClassColumnWidth column width in table output - storageClassColumnWidth int = 18 -) - -const ( - leftAlign int = 1 - centerAlign int = 2 - rightAlign int = 3 -) - -// Labels used for display. -const ( - idLabel string = "ID" - prefixLabel string = "Prefix" - statusLabel string = "Enabled " - expiryLabel string = "Expiry" - lifecycleDatesLabel string = "Date/Days " - tagLabel string = "Tags" - transitionLabel string = "Transition" - storageClassLabel string = "Tier " - typeLabel string = "Type" - versionLabel string = "Version " - unknownLabel string = "Unknown " -) - -// Keys to be used in map structure which stores the columns to be displayed. -const ( - statusLabelKey string = "Enabled" - storageClassLabelKey string = "Storage-Class" - ilmDatesLabelKey string = "ILM-Dates" -) - -// Some cell values -const ( - tickCell string = "✔ " - crossTickCell string = "✗ " - blankCell string = " " -) - -// Used in tags. Ex: --tags "key1=value1&key2=value2&key3=value3" -const ( - tagSeperator string = "&" - keyValSeperator string = "=" -) - -// Represents information going into a single cell in the table. -type tableCellInfo struct { - label string - multLabels []string - labelKey string - columnWidth int - align int -} - -// Determines what columns need to be shown -type showDetails struct { - allAvailable bool - expiry bool - transition 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, showExpiry, showTransition bool, -) { - // We need the different column headers and their respective column index - // where they appear in a map data-structure format. - // [Column Label] -> [Column Number] - *rowCheck = make(map[string]int) - // For rows with tags only tags are shown. Rest of the cells are empty (blanks in full cell length) - *tagRows = make(map[string][]string) - showOpts := showDetails{ - allAvailable: showAll, - expiry: showExpiry, - transition: showTransition, - } - getColumns(ilmCfg, *rowCheck, alignedHdrLabels, showOpts) - getILMShowDataWithoutTags(cellDataNoTags, *rowCheck, ilmCfg, showOpts) - getILMShowDataWithTags(cellDataWithTags, *tagRows, *rowCheck, ilmCfg, showOpts) -} - -// Text inside the table cell -func getAlignedText(label string, align int, columnWidth int) string { - cellLabel := blankCell - switch align { - case leftAlign: - cellLabel = getLeftAligned(label, columnWidth) - case centerAlign: - cellLabel = getCenterAligned(label, columnWidth) - case rightAlign: - cellLabel = getRightAligned(label, columnWidth) - } - return cellLabel -} - -// GetColumnWidthTable We will use this map of Header Labels -> Column width -func getILMColumnWidthTable() map[string]int { - colWidth := make(map[string]int) - - colWidth[idLabel] = idColumnWidth - colWidth[prefixLabel] = prefixColumnWidth - colWidth[statusLabelKey] = statusColumnWidth - colWidth[typeLabel] = typeColumnWidth - colWidth[versionLabel] = versionColumnWidth - colWidth[lifecycleDatesLabel] = ilmDatesColumnWidth - colWidth[storageClassLabelKey] = storageClassColumnWidth - colWidth[tagLabel] = tagsColumnWidth - - return colWidth -} - -// checkAddTableCellRows multiple rows created by filling up each cell of the table. -// Multiple rows are required for display of data with tags. -// Each 'key:value' pair is shown in 1 row and the rest of it is cells populated with blanks. -func checkAddTableCellRows(rowArr *[]string, rowCheck map[string]int, showOpts showDetails, - cellInfo tableCellInfo, ruleID string, newRows map[string][]string, -) { - var cellLabel string - multLth := len(cellInfo.multLabels) - if cellInfo.label != "" || multLth == 0 { - if colIdx, ok := rowCheck[cellInfo.labelKey]; ok { - (*rowArr)[colIdx] = getCenterAligned(blankCell, cellInfo.columnWidth) - } - return - } - colWidth := getILMColumnWidthTable() - - if colIdx, ok := rowCheck[cellInfo.labelKey]; ok { - cellLabel := cellInfo.multLabels[0] - if len(cellInfo.multLabels[0]) > (cellInfo.columnWidth - 3) { // 2 dots & 1 space for left-alignment - cellLabel = cellLabel[:(cellInfo.columnWidth-5)] + ".." - } - (*rowArr)[colIdx] = getLeftAligned(cellLabel, cellInfo.columnWidth) - } - - for index := 1; index < multLth; index++ { - row := make([]string, len(rowCheck)) - for k, v := range rowCheck { - if k == cellInfo.labelKey { - cellLabel = cellInfo.multLabels[index] - if len(cellInfo.multLabels[index]) > (cellInfo.columnWidth - 3) { - cellLabel = cellLabel[:(cellInfo.columnWidth-5)] + ".." - } - row[v] = getLeftAligned(cellLabel, cellInfo.columnWidth) - } else { - var width int - var ok bool - if width, ok = colWidth[k]; !ok { - width = 4 - } - row[v] = getCenterAligned(blankCell, width) - } - } - newRows[ruleID+strconv.Itoa(index-1)] = row - } -} - -// The right kind of tick is returned. Cross-tick if status is 'Disabled' & tick if status is 'Enabled'. -func getStatusTick(rule lifecycle.Rule) string { - statusTick := crossTickCell - if rule.Status == statusLabelKey { - statusTick = tickCell - } - return statusTick -} - -// Expiry date. 'YYYY-MM-DD'. Set for 00:00:00 GMT as per the standard. -func getLifeCycleDateVal(rule lifecycle.Rule) string { - columnDate := blankCell - // For Expiration Type Rules - if !rule.Expiration.IsDateNull() { - columnDate = strconv.Itoa(rule.Expiration.Date.Day()) + " " + - rule.Expiration.Date.Month().String()[0:3] + " " + - strconv.Itoa(rule.Expiration.Date.Year()) - } else if !rule.Expiration.IsDaysNull() { - columnDate = strconv.Itoa(int(rule.Expiration.Days)) + " day(s)" - } - - if !rule.Expiration.IsDateNull() { - columnDate = strconv.Itoa(rule.Expiration.Date.Day()) + " " + - rule.Expiration.Date.Month().String()[0:3] + " " + - strconv.Itoa(rule.Expiration.Date.Year()) - } else if !rule.Expiration.IsDaysNull() { - columnDate = strconv.Itoa(int(rule.Expiration.Days)) + " day(s)" - } - - if !rule.NoncurrentVersionExpiration.IsDaysNull() { - columnDate = strconv.Itoa(int(rule.NoncurrentVersionExpiration.NoncurrentDays)) + " day(s)" - } - - if !rule.Transition.IsDateNull() { - columnDate = strconv.Itoa(rule.Transition.Date.Day()) + " " + - rule.Transition.Date.Month().String()[0:3] + " " + - strconv.Itoa(rule.Transition.Date.Year()) - } else if !rule.Transition.IsDaysNull() { - columnDate = strconv.Itoa(int(rule.Transition.Days)) + " day(s)" - } - - if !rule.NoncurrentVersionTransition.IsDaysNull() { - columnDate = strconv.Itoa(int(rule.NoncurrentVersionTransition.NoncurrentDays)) + " day(s)" - } - - return columnDate -} - -// Returns whether the rule is Transition or Expiration -func getIlmRuleType(rule lifecycle.Rule) string { - if !rule.Transition.IsNull() { - return transitionLabel - } - if !rule.NoncurrentVersionTransition.IsDaysNull() { - return transitionLabel - } - if !rule.Expiration.IsNull() { - return expiryLabel - } - if !rule.NoncurrentVersionExpiration.IsDaysNull() { - return expiryLabel - } - return unknownLabel -} - -// Returns whether the rule is for current or non-current -func getTargetVersion(rule lifecycle.Rule) string { - if !rule.NoncurrentVersionTransition.IsDaysNull() { - return "Non-Current" - } - if !rule.Transition.IsNull() { - return "Current" - } - if !rule.NoncurrentVersionExpiration.IsDaysNull() { - return "Non-Current" - } - if !rule.Expiration.IsNull() { - return "Current" - } - return unknownLabel -} - -// Storage class name for transition. -func getStorageClassName(rule lifecycle.Rule) string { - storageClass := blankCell - transitionSet := !rule.Transition.IsNull() - storageClassAvail := transitionSet && (rule.Transition.StorageClass != "") - if storageClassAvail { - storageClass = rule.Transition.StorageClass - } - return storageClass -} - -// Array of Tag strings, each in key:value format -func getTagArr(rule lifecycle.Rule) []string { - var tagArr []lifecycle.Tag - switch { - case !rule.RuleFilter.Tag.IsEmpty(): - tagArr = []lifecycle.Tag{rule.RuleFilter.Tag} - case !rule.RuleFilter.And.IsEmpty(): - tagArr = rule.RuleFilter.And.Tags - default: - return []string{} - } - - tagLth := len(tagArr) - tagCellArr := make([]string, len(tagArr)) - for tagIdx := 0; tagIdx < tagLth; tagIdx++ { - tagCellArr[tagIdx] = (tagArr[tagIdx].Key + ":" + tagArr[tagIdx].Value) - } - return tagCellArr -} - -// Add single row table cell - non-header. -func checkAddTableCell(rowArr *[]string, rowCheck map[string]int, cellInfo tableCellInfo) { - if rowArr == nil { - return - } - if len(*rowArr) == 0 && len(rowCheck) > 0 { - *rowArr = make([]string, len(rowCheck)) - } - - if colIdx, ok := rowCheck[cellInfo.labelKey]; ok { - if len(cellInfo.label)%2 != 0 && len(cellInfo.label) < cellInfo.columnWidth { - cellInfo.label += " " - } else if len(cellInfo.label) > (cellInfo.columnWidth - 2) { // 2 dots to indicate text longer than column width - cellInfo.label = cellInfo.label[:(cellInfo.columnWidth-6)] + ".." - } - - (*rowArr)[colIdx] = getAlignedText(cellInfo.label, cellInfo.align, cellInfo.columnWidth) - } -} - -// GetILMShowDataWithoutTags - Without tags -func getILMShowDataWithoutTags(cellInfo *[][]string, rowCheck map[string]int, info *lifecycle.Configuration, showOpts showDetails) { - *cellInfo = make([][]string, 0) - count := 0 - for index := 0; index < len(info.Rules); index++ { - rule := info.Rules[index] - - // Ignore this rule if it has tag filter in it - if len(getTagArr(rule)) > 0 { - continue - } - - showExpiry := !rule.Expiration.IsNull() - transitionSet := !rule.Transition.IsNull() - skipExpTran := (showOpts.expiry && !showExpiry) || (showOpts.transition && !transitionSet) - if skipExpTran { - continue - } - - *cellInfo = append(*cellInfo, make([]string, 0)) - checkAddTableCell(&((*cellInfo)[count]), rowCheck, - tableCellInfo{label: rule.ID, labelKey: idLabel, columnWidth: idColumnWidth, align: leftAlign}) - checkAddTableCell(&((*cellInfo)[count]), rowCheck, - tableCellInfo{label: getIlmRuleType(rule), labelKey: typeLabel, columnWidth: typeColumnWidth, align: centerAlign}) - checkAddTableCell(&((*cellInfo)[count]), rowCheck, - tableCellInfo{label: getTargetVersion(rule), labelKey: versionLabel, columnWidth: versionColumnWidth, align: centerAlign}) - checkAddTableCell(&((*cellInfo)[count]), rowCheck, - tableCellInfo{label: getStorageClassName(rule), labelKey: storageClassLabelKey, columnWidth: storageClassColumnWidth, align: centerAlign}) - checkAddTableCell(&((*cellInfo)[count]), rowCheck, - tableCellInfo{label: getLifeCycleDateVal(rule), labelKey: ilmDatesLabelKey, columnWidth: ilmDatesColumnWidth, align: centerAlign}) - checkAddTableCell(&((*cellInfo)[count]), rowCheck, - tableCellInfo{label: getPrefixVal(rule), labelKey: prefixLabel, columnWidth: prefixColumnWidth, align: centerAlign}) - checkAddTableCell(&((*cellInfo)[count]), rowCheck, - tableCellInfo{label: getStatusTick(rule), labelKey: statusLabelKey, columnWidth: statusColumnWidth, align: centerAlign}) - - checkAddTableCell(&((*cellInfo)[count]), rowCheck, - tableCellInfo{label: blankCell, labelKey: tagLabel, columnWidth: tagsColumnWidth, align: centerAlign}) - count++ - } -} - -// GetILMShowDataWithTags Just the data with extra rows for extra tags -func getILMShowDataWithTags(cellInfo *[][]string, newRows map[string][]string, rowCheck map[string]int, info *lifecycle.Configuration, showOpts showDetails) { - *cellInfo = make([][]string, 0) - count := 0 - for index := 0; index < len(info.Rules); index++ { - rule := info.Rules[index] - - // Ignore printing this rule if it doesn't have any tag filter in it - if len(getTagArr(rule)) == 0 { - continue - } - - showExpiry := !rule.Expiration.IsNull() - transitionSet := !rule.Transition.IsNull() - skipExpTran := (showOpts.expiry && !showExpiry) || (showOpts.transition && !transitionSet) - if skipExpTran { - continue - } - - *cellInfo = append(*cellInfo, make([]string, 0)) - checkAddTableCell(&((*cellInfo)[count]), rowCheck, - tableCellInfo{label: rule.ID, labelKey: idLabel, columnWidth: idColumnWidth, align: leftAlign}) - checkAddTableCell(&((*cellInfo)[count]), rowCheck, - tableCellInfo{label: getIlmRuleType(rule), labelKey: typeLabel, columnWidth: versionColumnWidth, align: centerAlign}) - checkAddTableCell(&((*cellInfo)[count]), rowCheck, - tableCellInfo{label: getTargetVersion(rule), labelKey: versionLabel, columnWidth: typeColumnWidth, align: centerAlign}) - checkAddTableCell(&((*cellInfo)[count]), rowCheck, - tableCellInfo{label: getStorageClassName(rule), labelKey: storageClassLabelKey, columnWidth: storageClassColumnWidth, align: centerAlign}) - checkAddTableCell(&((*cellInfo)[count]), rowCheck, - tableCellInfo{label: getLifeCycleDateVal(rule), labelKey: ilmDatesLabelKey, columnWidth: ilmDatesColumnWidth, align: centerAlign}) - checkAddTableCell(&((*cellInfo)[count]), rowCheck, - tableCellInfo{label: getPrefixVal(rule), labelKey: prefixLabel, columnWidth: prefixColumnWidth, align: centerAlign}) - checkAddTableCell(&((*cellInfo)[count]), rowCheck, - tableCellInfo{label: getStatusTick(rule), labelKey: statusLabelKey, columnWidth: statusColumnWidth, align: centerAlign}) - - checkAddTableCellRows(&((*cellInfo)[count]), rowCheck, showOpts, - tableCellInfo{multLabels: getTagArr(rule), label: "", labelKey: tagLabel, columnWidth: tagsColumnWidth, align: leftAlign}, - rule.ID, newRows) - count++ - } -} - -func getPrefixVal(rule lifecycle.Rule) string { - prefixVal := "" - switch { - case rule.Prefix != "": - prefixVal = rule.Prefix - case !rule.RuleFilter.And.IsEmpty(): - prefixVal = rule.RuleFilter.And.Prefix - case rule.RuleFilter.Prefix != "": - prefixVal = rule.RuleFilter.Prefix - } - return prefixVal -} - -func showLifeCycleDetails(rule lifecycle.Rule, showOpts showDetails) bool { - if showOpts.allAvailable { - return true - } - expirySet := !rule.Expiration.IsNull() - - return (expirySet && (showOpts.allAvailable || showOpts.expiry)) -} - -func showTags(rule lifecycle.Rule, showOpts showDetails) bool { - tagSet := showOpts.allAvailable || !rule.RuleFilter.And.IsEmpty() - return tagSet -} - -func getColumns(info *lifecycle.Configuration, rowCheck map[string]int, alignedHdrLabels *[]string, showOpts showDetails) { - tagIn := false // Keep tag in the end - colIdx := 0 - colWidthTbl := getILMColumnWidthTable() - incColIdx := func() int { - if tagIn { - colIdx = rowCheck[tagLabel] - rowCheck[tagLabel] = colIdx + 1 - } else { - colIdx++ - } - return colIdx - } - - for index := 0; index < len(info.Rules); index++ { - rule := info.Rules[index] - _, ok := rowCheck[idLabel] - if !ok { // ID & Prefix are shown always. - rowCheck[idLabel] = colIdx - (*alignedHdrLabels) = append((*alignedHdrLabels), getAlignedText(idLabel, centerAlign, colWidthTbl[idLabel])) - } - _, ok = rowCheck[typeLabel] - if !ok { - rowCheck[typeLabel] = incColIdx() - (*alignedHdrLabels) = append((*alignedHdrLabels), getAlignedText(typeLabel, centerAlign, colWidthTbl[typeLabel])) - } - _, ok = rowCheck[versionLabel] - if !ok { - rowCheck[versionLabel] = incColIdx() - (*alignedHdrLabels) = append((*alignedHdrLabels), getAlignedText(versionLabel, centerAlign, colWidthTbl[versionLabel])) - } - _, ok = rowCheck[storageClassLabelKey] - if !ok { - rowCheck[storageClassLabelKey] = incColIdx() - (*alignedHdrLabels) = append((*alignedHdrLabels), getAlignedText(storageClassLabel, centerAlign, colWidthTbl[storageClassLabelKey])) - } - _, ok = rowCheck[ilmDatesLabelKey] - if !ok && showLifeCycleDetails(rule, showOpts) { - rowCheck[ilmDatesLabelKey] = incColIdx() - (*alignedHdrLabels) = append((*alignedHdrLabels), getAlignedText(lifecycleDatesLabel, centerAlign, colWidthTbl[ilmDatesLabelKey])) - } - _, ok = rowCheck[prefixLabel] - if !ok { // ID & Prefix are shown always. - rowCheck[prefixLabel] = incColIdx() - (*alignedHdrLabels) = append((*alignedHdrLabels), getAlignedText(prefixLabel, centerAlign, colWidthTbl[prefixLabel])) - } - _, ok = rowCheck[statusLabelKey] - if !ok { - rowCheck[statusLabelKey] = incColIdx() - (*alignedHdrLabels) = append((*alignedHdrLabels), getAlignedText(statusLabel, centerAlign, colWidthTbl[statusLabelKey])) - } - _, ok = rowCheck[tagLabel] - if !ok && showTags(rule, showOpts) { - rowCheck[tagLabel] = incColIdx() - tagIn = true - (*alignedHdrLabels) = append((*alignedHdrLabels), getAlignedText(tagLabel, centerAlign, colWidthTbl[tagLabel])) - } - } -} diff --git a/cmd/ilm/utils.go b/cmd/ilm/utils.go new file mode 100644 index 00000000..acb808f2 --- /dev/null +++ b/cmd/ilm/utils.go @@ -0,0 +1,141 @@ +// Copyright (c) 2022 MinIO, Inc. +// +// This file is part of MinIO Object Storage stack +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see . + +package ilm + +import ( + "fmt" + "strings" + "time" + + "github.com/minio/minio-go/v7/pkg/lifecycle" +) + +// getPrefix returns the prefix configured +func getPrefix(rule lifecycle.Rule) string { + // deprecated, but older ILM policies may have them + if rule.Prefix != "" { + return rule.Prefix + } + if rule.RuleFilter.Prefix != "" { + return rule.RuleFilter.Prefix + } + if rule.RuleFilter.And.Prefix != "" { + return rule.RuleFilter.And.Prefix + } + return "" +} + +// getTags returns the tags configured as "k1=v1&k2=v2" +func getTags(rule lifecycle.Rule) string { + if !rule.RuleFilter.Tag.IsEmpty() { + return fmt.Sprintf("%s=%s", rule.RuleFilter.Tag.Key, rule.RuleFilter.Tag.Value) + } + if len(rule.RuleFilter.And.Tags) > 0 { + var tags strings.Builder + for i, tag := range rule.RuleFilter.And.Tags { + fmt.Fprintf(&tags, "%s=%s", tag.Key, tag.Value) + if i < len(rule.RuleFilter.And.Tags)-1 { + fmt.Fprintf(&tags, "&") + } + } + return tags.String() + } + return "" +} + +// getExpirationDays returns the number of days to expire relative to +// time.Now().UTC() for the given rule. +func getExpirationDays(rule lifecycle.Rule) int { + if rule.Expiration.Days > 0 { + return int(rule.Expiration.Days) + } + if !rule.Expiration.Date.Time.IsZero() { + return int(time.Now().UTC().Sub(rule.Expiration.Date.Time).Hours() / 24) + } + + return 0 +} + +// getTransitionDays returns the number of days to transition/tier relative to +// time.Now().UTC() for the given rule. +func getTransitionDays(rule lifecycle.Rule) int { + if !rule.Transition.Date.IsZero() { + return int(time.Now().UTC().Sub(rule.Transition.Date.Time).Hours() / 24) + } + + return int(rule.Transition.Days) +} + +// ToTables converts a lifecycle.Configuration into its tabular representation. +func ToTables(cfg *lifecycle.Configuration, filter LsFilter) []Table { + var tierCur tierCurrentTable + var tierNoncur tierNoncurrentTable + var expCur expirationCurrentTable + var expNoncur expirationNoncurrentTable + for _, rule := range cfg.Rules { + if !rule.Expiration.IsNull() { + expCur = append(expCur, expirationCurrentRow{ + ID: rule.ID, + Status: rule.Status, + Prefix: getPrefix(rule), + Tags: getTags(rule), + Days: getExpirationDays(rule), + ExpireDelMarker: false, + }) + } + if !rule.NoncurrentVersionExpiration.IsDaysNull() { + expNoncur = append(expNoncur, expirationNoncurrentRow{ + ID: rule.ID, + Status: rule.Status, + Prefix: getPrefix(rule), + Tags: getTags(rule), + Days: int(rule.NoncurrentVersionExpiration.NoncurrentDays), + KeepVersions: rule.NoncurrentVersionExpiration.NewerNoncurrentVersions, + }) + } + if !rule.Transition.IsNull() { + tierCur = append(tierCur, tierCurrentRow{ + ID: rule.ID, + Status: rule.Status, + Prefix: getPrefix(rule), + Tags: getTags(rule), + Days: getTransitionDays(rule), + Tier: rule.Transition.StorageClass, + }) + } + if !rule.NoncurrentVersionTransition.IsStorageClassEmpty() { + tierNoncur = append(tierNoncur, tierNoncurrentRow{ + ID: rule.ID, + Status: rule.Status, + Prefix: getPrefix(rule), + Tags: getTags(rule), + Days: int(rule.NoncurrentVersionTransition.NoncurrentDays), + Tier: rule.NoncurrentVersionTransition.StorageClass, + }) + } + } + + switch filter { + case ExpiryOnly: + return []Table{expCur, expNoncur} + case TransitionOnly: + return []Table{tierCur, tierNoncur} + default: + return []Table{tierCur, tierNoncur, expCur, expNoncur} + } +} diff --git a/cmd/ilm/utils_test.go b/cmd/ilm/utils_test.go new file mode 100644 index 00000000..0e907880 --- /dev/null +++ b/cmd/ilm/utils_test.go @@ -0,0 +1,73 @@ +// Copyright (c) 2022 MinIO, Inc. +// +// This file is part of MinIO Object Storage stack +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see . + +package ilm + +import ( + "testing" + + "github.com/minio/minio-go/v7/pkg/lifecycle" +) + +func TestILMTags(t *testing.T) { + tests := []struct { + rule lifecycle.Rule + expected string + }{ + { + rule: lifecycle.Rule{ + ID: "one-tag", + RuleFilter: lifecycle.Filter{ + Tag: lifecycle.Tag{ + Key: "key1", + Value: "val1", + }, + }, + }, + expected: "key1=val1", + }, + { + rule: lifecycle.Rule{ + ID: "many-tags", + RuleFilter: lifecycle.Filter{ + And: lifecycle.And{ + Tags: []lifecycle.Tag{ + { + Key: "key1", + Value: "val1", + }, + { + Key: "key2", + Value: "val2", + }, + { + Key: "key3", + Value: "val3", + }, + }, + }, + }, + }, + expected: "key1=val1&key2=val2&key3=val3", + }, + } + for i, test := range tests { + if got := getTags(test.rule); got != test.expected { + t.Fatalf("%d: Expected %s but got %s", i+1, test.expected, got) + } + } +} diff --git a/go.mod b/go.mod index 868ecb5d..275dfed9 100644 --- a/go.mod +++ b/go.mod @@ -69,6 +69,7 @@ require ( github.com/golang/protobuf v1.5.2 // indirect github.com/hashicorp/errwrap v1.1.0 // indirect github.com/hashicorp/go-multierror v1.1.1 // indirect + github.com/jedib0t/go-pretty/v6 v6.3.8 github.com/klauspost/cpuid/v2 v2.1.2 // indirect github.com/kr/text v0.2.0 // indirect github.com/lestrrat-go/backoff/v2 v2.0.8 // indirect diff --git a/go.sum b/go.sum index b685a36f..5f7d53ac 100644 --- a/go.sum +++ b/go.sum @@ -416,6 +416,8 @@ github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1: github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= github.com/inconshreveable/mousetrap v1.0.1 h1:U3uMjPSQEBMNp1lFxmllqCPM6P5u/Xq7Pgzkat/bFNc= github.com/inconshreveable/mousetrap v1.0.1/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= +github.com/jedib0t/go-pretty/v6 v6.3.8 h1:p5eZqLFMEGr7CC+9915lC4Dk7Gub6mH7NE35jDhkJsQ= +github.com/jedib0t/go-pretty/v6 v6.3.8/go.mod h1:MgmISkTWDSFu0xOqiZ0mKNntMQ2mDgOcwOkwBEkMDJI= github.com/jpillora/backoff v1.0.0/go.mod h1:J/6gKK9jxlEcS3zixgDgUAsiuZ7yrSoa/FX5e0EB2j4= github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= github.com/json-iterator/go v1.1.10/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= @@ -563,6 +565,7 @@ github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINE github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pkg/profile v1.6.0/go.mod h1:qBsxPvzyUincmltOk6iyRVxHYg4adc0OFOv72ZdLa18= github.com/pkg/sftp v1.10.1/go.mod h1:lYOWFsE0bwd1+KfKJaKeuokY15vzFx25BLbzYYoAxZI= github.com/pkg/xattr v0.4.9 h1:5883YPCtkSd8LFbs13nXplj9g9tlrwoJRjgpgMu1/fE= github.com/pkg/xattr v0.4.9/go.mod h1:di8WF84zAKk8jzR1UBTEWh9AUlIZZ7M/JNt8e9B6ktU= @@ -654,6 +657,7 @@ github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/ github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.2/go.mod h1:R6va5+xMeoiuVRoj+gSkQ7d3FALtqAAGI1FQKckRals= +github.com/stretchr/testify v1.7.4/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= github.com/stretchr/testify v1.8.0 h1:pSgiaMZlXftHpm5L7V1+rVB+AZJydKsMxsQBIJw4PKk= github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= github.com/subosito/gotenv v1.2.0/go.mod h1:N0PQaV/YGNqwC0u51sEeR/aUtSLEXKX9iv69rRypqCw=