diff --git a/cmd/client-fs.go b/cmd/client-fs.go index 21da618e..3318d578 100644 --- a/cmd/client-fs.go +++ b/cmd/client-fs.go @@ -1126,3 +1126,19 @@ func (f *fsClient) DeleteObjectTagging() *probe.Error { APIType: "filesystem", }) } + +// Get lifecycle configuration for a given bucket. +func (f *fsClient) GetBucketLifecycle() (string, *probe.Error) { + return "", probe.NewError(APINotImplemented{ + API: "GetBucketLifecycle", + APIType: "filesystem", + }) +} + +// Set lifecycle configuration for a given bucket. +func (f *fsClient) SetBucketLifecycle(lifecycleconfig string) *probe.Error { + return probe.NewError(APINotImplemented{ + API: "SetBucketLifecycle", + APIType: "filesystem", + }) +} diff --git a/cmd/client-s3.go b/cmd/client-s3.go index 92ce088a..2c14c6cb 100644 --- a/cmd/client-s3.go +++ b/cmd/client-s3.go @@ -2270,3 +2270,24 @@ func (c *S3Client) DeleteObjectTagging() *probe.Error { } return nil } + +// GetBucketLifecycle - Get lifecycle configuration for a given bucket. +func (c *S3Client) GetBucketLifecycle() (string, *probe.Error) { + bucket, _ := c.url2BucketAndObject() + + lifecycleXML, err := c.api.GetBucketLifecycle(bucket) + if err != nil { + return "", probe.NewError(err) + } + return lifecycleXML, nil +} + +// SetBucketLifecycle - Set lifecycle configuration for a given bucket. +func (c *S3Client) SetBucketLifecycle(lifecycleXML string) *probe.Error { + bucket, _ := c.url2BucketAndObject() + err := c.api.SetBucketLifecycle(bucket, lifecycleXML) + if err != nil { + return probe.NewError(err) + } + return nil +} diff --git a/cmd/client.go b/cmd/client.go index de6336c5..b494b3aa 100644 --- a/cmd/client.go +++ b/cmd/client.go @@ -92,6 +92,9 @@ type Client interface { GetObjectTagging() (tagging.Tagging, *probe.Error) SetObjectTagging(tagMap map[string]string) *probe.Error DeleteObjectTagging() *probe.Error + // Bucket Lifecycle operations + GetBucketLifecycle() (string, *probe.Error) + SetBucketLifecycle(lifecycleXML string) *probe.Error } // ClientContent - Content container for content metadata diff --git a/cmd/ilm-add.go b/cmd/ilm-add.go new file mode 100644 index 00000000..a1e0413b --- /dev/null +++ b/cmd/ilm-add.go @@ -0,0 +1,165 @@ +/* + * MinIO Client (C) 2020 MinIO, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cmd + +import ( + "errors" + "os" + + "github.com/minio/cli" + "github.com/minio/mc/cmd/ilm" + json "github.com/minio/mc/pkg/colorjson" + "github.com/minio/mc/pkg/probe" + "github.com/minio/minio/pkg/console" +) + +var ilmAddCmd = cli.Command{ + Name: "add", + Usage: "add a lifecycle configuration rule to existing (if any) rules of the bucket", + Action: mainILMAdd, + Before: setGlobalsFromContext, + Flags: append(ilmAddFlags, globalFlags...), + CustomHelpTemplate: `Name: + {{.HelpName}} - {{.Usage}} + +USAGE: + {{.HelpName}} [COMMAND FLAGS] TARGET + +FLAGS: + {{range .VisibleFlags}}{{.}} + {{end}} +DESCRIPTION: + ILM add command appends one rule to the existing set of lifecycle configuration rules. If a rule with the ID already exists it will be replaced. + +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 + + 2. Add rule for testbucket on s3. Both expiry and transition are number of days. + {{.Prompt}} {{.HelpName}} --id "Docs" --prefix "doc/" --expiry-days "200" --transition-days "300 days" --storage-class "GLACIER" s3/testbucket + + 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 + +`, +} + +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", + }, + 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 ilmAddMessage struct { + Status string `json:"status"` + Target string `json:"target"` + ID string `json:"id"` +} + +func (i ilmAddMessage) String() string { + return console.Colorize(ilmThemeResultSuccess, "Lifecycle configuration rule added with ID `"+i.ID+"` to "+i.Target+".") +} + +func (i ilmAddMessage) JSON() string { + msgBytes, e := json.MarshalIndent(i, "", " ") + fatalIf(probe.NewError(e), "Unable to marshal into JSON.") + return string(msgBytes) +} + +// Validate user given arguments +func checkILMAddSyntax(ctx *cli.Context) { + if len(ctx.Args()) != 1 { + cli.ShowCommandHelp(ctx, "add") + os.Exit(globalErrorExitStatus) + } + id := ctx.String("id") + if id == "" { + e := errors.New("ID for a rule cannot be empty") + fatalIf(probe.NewError(e), "Refer mc "+ctx.Command.FullName()+" --help for more details") + } +} + +// Calls SetBucketLifecycle with the XML representation of lifecycleConfiguration type. +func mainILMAdd(ctx *cli.Context) error { + var err error + checkILMAddSyntax(ctx) + setILMDisplayColorScheme() + args := ctx.Args() + objectURL := args.Get(0) + id := ctx.String("id") + // Configuration that is already set. + lfcInfoXML, pErr := getBucketILMConfiguration(objectURL) + fatalIf(pErr, "Failed to generate lifecycle configuration for "+objectURL) + ilmID := ctx.String("id") + ilmPrefix := ctx.String("prefix") + ilmStatus := "Enabled" + if ilmDisable := ctx.Bool("disable"); ilmDisable { + ilmStatus = "Disabled" + } + ilmTag := ctx.String("tags") + ilmExpiryDate := ctx.String("expiry-date") + ilmExpiryDays := ctx.String("expiry-days") + ilmTransitionDate := ctx.String("transition-date") + ilmTransitionDays := ctx.String("transition-days") + ilmStorageClass := ctx.String("storage-class") + // Configuration that needs to be set is returned by ilm.GetILMConfigToSet. + // A new rule is added or the rule (if existing) is replaced + lfcInfoXML, err = ilm.GetILMConfigToSet(lfcInfoXML, ilmID, ilmPrefix, ilmStatus, ilmTag, + ilmExpiryDate, ilmExpiryDays, ilmTransitionDate, ilmTransitionDays, ilmStorageClass) + fatalIf(probe.NewError(err), "Failed to get lifecycle configuration from the user input") + pErr = setBucketILMConfiguration(objectURL, lfcInfoXML) + fatalIf(pErr, "Failed to set lifecycle rule with id `"+id+"`") + printMsg(ilmAddMessage{ + Status: "success", + Target: objectURL, + ID: id, + }) + return nil +} diff --git a/cmd/ilm-export.go b/cmd/ilm-export.go new file mode 100644 index 00000000..d2db64ae --- /dev/null +++ b/cmd/ilm-export.go @@ -0,0 +1,106 @@ +/* + * MinIO Client (C) 2020 MinIO, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cmd + +import ( + "os" + + "github.com/minio/cli" + "github.com/minio/mc/cmd/ilm" + json "github.com/minio/mc/pkg/colorjson" + "github.com/minio/mc/pkg/probe" + "github.com/minio/minio/pkg/console" +) + +var ilmExportCmd = cli.Command{ + Name: "export", + Usage: "export lifecycle configuration in JSON format", + Action: mainILMExport, + Before: setGlobalsFromContext, + Flags: globalFlags, + CustomHelpTemplate: `Name: + {{.HelpName}} - {{.Usage}} + +USAGE: + {{.HelpName}} TARGET + +DESCRIPTION: + Lifecycle configuration of the target bucket exported in JSON format. + +EXAMPLES: + 1. Redirect output of lifecycle configuration rules of the testbucket on alias s3 to the file lifecycle.json + {{.Prompt}} {{.HelpName}} s3/testbucket >> /Users/miniouser/Documents/lifecycle.json + 2. Show lifecycle configuration rules of the testbucket on alias s3 on STDOUT + {{.Prompt}} {{.HelpName}} s3/testbucket + +`, +} + +type ilmExportMessage struct { + Status string `json:"status"` + Target string `json:"target"` + ILMConfig string `json:"-"` + ILM ilm.LifecycleConfiguration `json:"ilm"` +} + +func (i ilmExportMessage) String() string { + var ilmRet string + var e error + if i.ILMConfig == "" { + return console.Colorize(ilmThemeResultFailure, "Lifecycle configuration is not set.") + } + if ilmRet, e = ilm.GetILMJSON(i.ILMConfig); e != nil { + return console.Colorize(ilmThemeResultFailure, e.Error()+". Export failed.") + } + return ilmRet +} + +func (i ilmExportMessage) JSON() string { + msgBytes, e := json.MarshalIndent(i, "", " ") + fatalIf(probe.NewError(e), "Unable to marshal into JSON.") + return string(msgBytes) +} + +// checkILMExportSyntax - validate arguments passed by user +func checkILMExportSyntax(ctx *cli.Context) { + if len(ctx.Args()) != 1 { + cli.ShowCommandHelp(ctx, "export") + os.Exit(globalErrorExitStatus) + } +} + +func mainILMExport(ctx *cli.Context) error { + checkILMExportSyntax(ctx) + setILMDisplayColorScheme() + var ilmConfiguration ilm.LifecycleConfiguration + var err error + args := ctx.Args() + objectURL := args.Get(0) + ilmInfoXML, pErr := getBucketILMConfiguration(objectURL) + fatalIf(pErr.Trace(), "Error exporting lifecycle configuration for "+objectURL+".") + if globalJSON { + ilmConfiguration, err = ilm.GetILMConfig(ilmInfoXML) + fatalIf(probe.NewError(err), "Error exporting lifecycle configuration.") + } + printMsg(ilmExportMessage{ + Status: "success", + Target: objectURL, + ILMConfig: ilmInfoXML, + ILM: ilmConfiguration, + }) + return nil +} diff --git a/cmd/ilm-import.go b/cmd/ilm-import.go new file mode 100644 index 00000000..3162ac11 --- /dev/null +++ b/cmd/ilm-import.go @@ -0,0 +1,116 @@ +/* + * 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 ( + "encoding/xml" + "errors" + "io" + "os" + + "github.com/minio/cli" + "github.com/minio/mc/cmd/ilm" + json "github.com/minio/mc/pkg/colorjson" + "github.com/minio/mc/pkg/probe" + "github.com/minio/minio/pkg/console" +) + +var ilmImportCmd = cli.Command{ + Name: "import", + Usage: "import lifecycle configuration in JSON format", + Action: mainILMImport, + Before: setGlobalsFromContext, + Flags: globalFlags, + CustomHelpTemplate: `Name: + {{.HelpName}} - {{.Usage}} + +USAGE: + {{.HelpName}} TARGET + +DESCRIPTION: + Lifecycle configuration is imported. Input is required in JSON format. + +EXAMPLES: + 1. Set lifecycle configuration for the testbucket on alias s3 to the rules imported from lifecycle.json + {{.Prompt}} {{.HelpName}} s3/testbucket < /Users/miniouser/Documents/lifecycle.json + 2. Set lifecycle configuration for the testbucket on alias s3. User is expected to enter the JSON contents on STDIN + {{.Prompt}} {{.HelpName}} s3/testbucket + +`, +} + +type ilmImportMessage struct { + Status string `json:"status"` + Target string `json:"target"` +} + +func (i ilmImportMessage) String() string { + return console.Colorize(ilmThemeResultSuccess, "Lifecycle configuration imported successfully to `"+i.Target+"`.") +} + +func (i ilmImportMessage) JSON() string { + msgBytes, e := json.MarshalIndent(i, "", " ") + fatalIf(probe.NewError(e), "Unable to marshal into JSON.") + return string(msgBytes) +} + +// ReadILMConfigJSON read from stdin and set ILM configuration to bucket +func readILMConfigJSON() (string, *probe.Error) { + // User is expected to enter the lifecycleConfiguration instance contents in JSON format + var ilmInfo ilm.LifecycleConfiguration + var bytes []byte + var err error + // Consume json from STDIN + dec := json.NewDecoder(os.Stdin) + if err = dec.Decode(&ilmInfo); err != nil && err != io.EOF { + return "", probe.NewError(err) + } + if len(ilmInfo.Rules) == 0 { + return "", probe.NewError(errors.New("Empty configuration")) + } + if bytes, err = xml.Marshal(ilmInfo); err != nil { + return "", probe.NewError(err) + } + + return string(bytes), nil +} + +// checkILMImportSyntax - validate arguments passed by user +func checkILMImportSyntax(ctx *cli.Context) { + if len(ctx.Args()) != 1 { + cli.ShowCommandHelp(ctx, "import") + os.Exit(globalErrorExitStatus) + } +} + +func mainILMImport(ctx *cli.Context) error { + checkILMImportSyntax(ctx) + setILMDisplayColorScheme() + + args := ctx.Args() + objectURL := args.Get(0) + var ilmXML string + ilmXML, pErr := readILMConfigJSON() + fatalIf(pErr, "Failed to read lifecycle configuration.") + pErr = setBucketILMConfiguration(objectURL, ilmXML) + fatalIf(pErr, "Failed to set lifecycle configuration.") + printMsg(ilmImportMessage{ + Status: "success", + Target: objectURL, + }) + return nil +} diff --git a/cmd/ilm-list.go b/cmd/ilm-list.go new file mode 100644 index 00000000..f41469ac --- /dev/null +++ b/cmd/ilm-list.go @@ -0,0 +1,284 @@ +/* + * MinIO Client (C) 2020 MinIO, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cmd + +import ( + "bytes" + "errors" + "os" + "strconv" + "strings" + + "github.com/minio/cli" + "github.com/minio/mc/cmd/ilm" + json "github.com/minio/mc/pkg/colorjson" + "github.com/minio/mc/pkg/probe" + "github.com/minio/minio/pkg/console" +) + +var ilmListFlags = []cli.Flag{ + cli.BoolFlag{ + Name: "expiry", + Usage: "show only expiration fields", + }, + cli.BoolFlag{ + Name: "transition", + Usage: "show only transition fields", + }, + cli.BoolFlag{ + Name: "minimum", + Usage: "show minimum fields - id, prefix, status, transition set, expiry set", + }, +} + +var ilmListCmd = cli.Command{ + Name: "list", + Usage: "list bucket lifecycle configuration", + Action: mainILMList, + Before: setGlobalsFromContext, + Flags: append(ilmListFlags, globalFlags...), + CustomHelpTemplate: `Name: + {{.HelpName}} - {{.Usage}} + +USAGE: + {{.HelpName}} [COMMAND FLAGS] TARGET + +FLAGS: + {{range .VisibleFlags}}{{.}} + {{end}} +DESCRIPTION: + ILM list command displays current lifecycle configuration. + +EXAMPLES: + 1. List the lifecycle management rules (all fields) for testbucket on alias s3. + {{.Prompt}} {{.HelpName}} s3/testbucket + + 2. List the lifecycle management rules (expration date/days fields) for testbucket on alias s3. + {{.Prompt}} {{.HelpName}} --expiry s3/testbucket + + 3. List the lifecycle management rules (transition date/days, storage class fields) for testbucket on alias s3. + {{.Prompt}} {{.HelpName}} --transition s3/testbucket + + 4. List the lifecycle management rules (minimum details) for testbucket on alias s3. + {{.Prompt}} {{.HelpName}} --minimum s3/testbucket + + 5. List the lifecycle management rules in JSON format for testbucket on alias s3. + {{.Prompt}} {{.HelpName}} --json s3/testbucket + +`, +} + +type ilmListMessage struct { + Status string `json:"status"` + Target string `json:"target"` + ILMConfig string `json:"-"` + ILM ilm.LifecycleConfiguration `json:"ilm"` +} + +func (i ilmListMessage) String() string { + if i.ILMConfig == "" { + return console.Colorize(ilmThemeResultFailure, "Lifecycle configuration for `"+i.Target+"` not set.") + } + return i.ILMConfig +} + +func (i ilmListMessage) JSON() string { + msgBytes, e := json.MarshalIndent(i, "", " ") + fatalIf(probe.NewError(e), "Unable to marshal into JSON.") + return string(msgBytes) +} + +// validateILMListFlagSet - Only one of these flags needs to be set for display: --json, --expiry, --transition, --minimum +func validateILMListFlagSet(ctx *cli.Context) bool { + var flags = [...]bool{ctx.Bool("expiry"), ctx.Bool("transition"), ctx.Bool("json"), + ctx.Bool("minimum")} + found := false + for _, flag := range flags { + if found && flag { + return false + } else if flag { + found = true + } + } + return true +} + +// checkILMListSyntax - validate arguments passed by a user +func checkILMListSyntax(ctx *cli.Context) { + if len(ctx.Args()) != 1 { + cli.ShowCommandHelp(ctx, "list") + os.Exit(globalErrorExitStatus) + } + if !validateILMListFlagSet(ctx) { + fatalIf(probe.NewError(errors.New("Invalid input flag(s)")), "Only one show field flag allowed for list command. Refer mc "+ctx.Command.FullName()+" --help.") + } +} + +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(ctx *cli.Context) error { + checkILMListSyntax(ctx) + setILMDisplayColorScheme() + var err error + var hdrLabelIndexMap map[string]int + var alignedHdrLabels []string + var cellDataNoTags [][]string + var cellDataWithTags [][]string + var tagRows map[string][]string + var tbl PrettyTable + args := ctx.Args() + objectURL := args.Get(0) + lfcInfo, pErr := getBucketILMConfiguration(objectURL) + fatalIf(pErr.Trace(objectURL), "Failed to list lifecycle configuration for "+objectURL) + showExpiry := ctx.Bool("expiry") + showTransition := ctx.Bool("transition") + showMinimum := ctx.Bool("minimum") + // If none of the flags are explicitly mentioned, all fields are shown. + showAll := !showExpiry && !showTransition && !showMinimum + + err = ilm.GetILMDataForShow(lfcInfo, &hdrLabelIndexMap, &alignedHdrLabels, + &cellDataNoTags, &cellDataWithTags, &tagRows, + showAll, showMinimum, showExpiry, showTransition) + fatalIf(probe.NewError(err), "Error getting tabular data for ILM configuration.") + // The header table + var fields []Field + // Fill up fields + var tblContents string + var ilmConfig ilm.LifecycleConfiguration + if len(cellDataNoTags) == 0 && len(cellDataWithTags) == 0 { + dataStr := "" + if showTransition { + dataStr = "Transition " + } else if showExpiry { + dataStr = "Expiry " + } + fatalIf(probe.NewError(errors.New(dataStr+"Lifecycle configuration not set")), + "Failed to list lifecycle configuration for "+objectURL+".") + } + + if !globalJSON { + for _, hdr := range alignedHdrLabels { + fields = append(fields, Field{ilmThemeHeader, len(hdr)}) + } + tbl = newPrettyTable(tableSeperator, fields...) + tblContents = getILMHeader(&tbl, alignedHdrLabels...) + fields = nil + // The data table + var tblRowField *[]string + if len(cellDataNoTags) == 0 { + tblRowField = &cellDataWithTags[0] + } else { + tblRowField = &cellDataNoTags[0] + } + for _, hdr := range *tblRowField { + fields = append(fields, Field{ilmThemeRow, len(hdr)}) + } + tbl = newPrettyTable(tableSeperator, fields...) + tblContents += getILMRowsNoTags(&tbl, &cellDataNoTags) + tblContents += getILMRowsWithTags(&tbl, &cellDataWithTags, tagRows) + + } else { + ilmConfig, err = ilm.GetILMConfig(lfcInfo) + fatalIf(probe.NewError(err), "Failed to get lifecycle configuration for "+objectURL+".") + } + printMsg(ilmListMessage{ + Status: "success", + Target: objectURL, + ILMConfig: tblContents, + ILM: ilmConfig, + }) + + return nil +} diff --git a/cmd/ilm-main.go b/cmd/ilm-main.go new file mode 100644 index 00000000..108d587b --- /dev/null +++ b/cmd/ilm-main.go @@ -0,0 +1,94 @@ +/* + * MinIO Client (C) 2020 MinIO, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cmd + +import ( + "github.com/fatih/color" + "github.com/minio/cli" + "github.com/minio/mc/pkg/probe" + "github.com/minio/minio/pkg/console" +) + +var ilmCmd = cli.Command{ + Name: "ilm", + Usage: "configure bucket lifecycle", + Action: mainILM, + Before: setGlobalsFromContext, + Flags: globalFlags, + Subcommands: []cli.Command{ + ilmListCmd, + ilmAddCmd, + ilmRemoveCmd, + ilmExportCmd, + ilmImportCmd, + }, +} + +const ( + ilmMainHeader string = "Main-Heading" + ilmThemeHeader string = "Row-Header" + ilmThemeRow string = "Row-Normal" + ilmThemeTick string = "Row-Tick" + ilmThemeExpiry string = "Row-Expiry" + ilmThemeResultSuccess string = "SuccessOp" + ilmThemeResultFailure string = "FailureOp" +) + +func mainILM(ctx *cli.Context) error { + cli.ShowCommandHelp(ctx, "") + return nil +} + +// setBucketILMConfiguration sets the lifecycle configuration given by ilmConfig to the bucket given by the url (urlStr) +func setBucketILMConfiguration(urlStr string, ilmConfig string) *probe.Error { + client, pErr := newClient(urlStr) + fatalIf(pErr, "Failed to set lifecycle configuration to "+urlStr) + s3c, ok := client.(*S3Client) + if !ok { + fatalIf(errDummy().Trace(urlStr), "For "+urlStr+" unable to obtain client reference.") + } + if pErr = s3c.SetBucketLifecycle(ilmConfig); pErr != nil { + return pErr + } + return nil +} + +// getBucketILMConfiguration gets the lifecycle configuration for the bucket given by the url (urlStr) +func getBucketILMConfiguration(urlStr string) (string, *probe.Error) { + var bktConfig string + client, pErr := newClient(urlStr) + fatalIf(pErr, "Failed to get lifecycle configuration to "+urlStr) + s3c, ok := client.(*S3Client) + if !ok { + fatalIf(errDummy().Trace(urlStr), "For "+urlStr+" unable to obtain client reference.") + } + if bktConfig, pErr = s3c.GetBucketLifecycle(); pErr != nil { + return "", pErr + } + return bktConfig, nil +} + +// Color scheme for the table +func setILMDisplayColorScheme() { + console.SetColor(ilmMainHeader, color.New(color.Bold, color.FgHiRed)) + console.SetColor(ilmThemeRow, color.New(color.FgHiWhite)) + console.SetColor(ilmThemeHeader, color.New(color.Bold, color.FgHiGreen)) + console.SetColor(ilmThemeTick, color.New(color.FgGreen)) + console.SetColor(ilmThemeExpiry, color.New(color.BlinkRapid, color.FgGreen)) + console.SetColor(ilmThemeResultSuccess, color.New(color.FgGreen, color.Bold)) + console.SetColor(ilmThemeResultFailure, color.New(color.FgHiYellow, color.Bold)) +} diff --git a/cmd/ilm-remove.go b/cmd/ilm-remove.go new file mode 100644 index 00000000..521aeb1f --- /dev/null +++ b/cmd/ilm-remove.go @@ -0,0 +1,178 @@ +/* + * MinIO Client (C) 2020 MinIO, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cmd + +import ( + "errors" + "os" + + "github.com/minio/cli" + "github.com/minio/mc/cmd/ilm" + json "github.com/minio/mc/pkg/colorjson" + "github.com/minio/mc/pkg/probe" + "github.com/minio/minio/pkg/console" +) + +var ilmRemoveFlags = []cli.Flag{ + cli.StringFlag{ + Name: "id", + Usage: "id of the lifecycle rule", + }, + cli.BoolFlag{ + Name: "force", + Usage: "force flag is to be used when deleting all lifecycle configuration rules for the bucket", + }, + cli.BoolFlag{ + Name: "all", + Usage: "delete all lifecycle configuration rules of the bucket, force flag enforced", + }, +} + +var ilmRemoveCmd = cli.Command{ + Name: "remove", + Usage: "remove (if any) existing lifecycle configuration rule with the id", + Action: mainILMRemove, + Before: setGlobalsFromContext, + Flags: append(ilmRemoveFlags, globalFlags...), + CustomHelpTemplate: `Name: + {{.HelpName}} - {{.Usage}} + +USAGE: + {{.HelpName}} [COMMAND FLAGS] TARGET + +FLAGS: + {{range .VisibleFlags}}{{.}} + {{end}} + +DESCRIPTION: + Remove the lifecycle configuration rule for the bucket with the ID or all configurations only if specified (--all --force). + + +EXAMPLES: + 1. Remove the lifecycle management configuration rule given by ID "Documents" for testbucket on alias s3. ID is case sensitive. + {{.Prompt}} {{.HelpName}} --id "Documents" s3/testbucket + 2. Remove ALL the lifecycle management configuration rules for testbucket on alias s3. Because the result is complete removal, the use of --force flag is enforced. + {{.Prompt}} {{.HelpName}} --all --force s3/testbucket + + +`, +} + +type ilmRmMessage struct { + Status string `json:"status"` + ID string `json:"id"` + Target string `json:"target"` + All bool `json:"all"` +} + +func (i ilmRmMessage) String() string { + msg := "Rule ID `" + i.ID + "` from target " + i.Target + " removed." + if i.All { + msg = "Rules for `" + i.Target + "` removed." + } + return console.Colorize(ilmThemeResultSuccess, msg) +} + +func (i ilmRmMessage) JSON() string { + msgBytes, e := json.MarshalIndent(i, "", " ") + fatalIf(probe.NewError(e), "Unable to marshal into JSON.") + return string(msgBytes) +} + +func checkILMRemoveSyntax(ctx *cli.Context) { + if len(ctx.Args()) != 1 { + cli.ShowCommandHelp(ctx, "remove") + os.Exit(globalErrorExitStatus) + } + ilmAll := ctx.Bool("all") + ilmForce := ctx.Bool("force") + forceChk := (ilmAll && ilmForce) || (!ilmAll && !ilmForce) + if !forceChk { + fatalIf(probe.NewError(errors.New("Flag missing or wrong")), + "Mandatory to enter --all and --force flag together for mc "+ctx.Command.FullName()+".") + } + if ilmAll && ilmForce { + return + } + ilmID := ctx.String("id") + if ilmID == "" { + fatalIf(probe.NewError(errors.New("ID of lifecycle rule missing")), "Please provide id.") + } +} + +func ilmAllRemove(urlStr string) *probe.Error { + if err := setBucketILMConfiguration(urlStr, ""); err != nil { + return err + } + return nil +} + +func ilmIDRemove(ilmID string, urlStr string) *probe.Error { + var lfcInfoXML string + var err error + var pErr *probe.Error + if lfcInfoXML, pErr = getBucketILMConfiguration(urlStr); err != nil { + return pErr + } + if lfcInfoXML == "" { + return probe.NewError(errors.New("Lifecycle configuration for `" + urlStr + "` not set")) + } + if lfcInfoXML, err = ilm.RemoveILMRule(lfcInfoXML, ilmID); err != nil { + return probe.NewError(err) + } + if pErr = setBucketILMConfiguration(urlStr, lfcInfoXML); err != nil { + return pErr + } + + return nil +} + +func mainILMRemove(ctx *cli.Context) error { + checkILMRemoveSyntax(ctx) + setILMDisplayColorScheme() + args := ctx.Args() + objectURL := args.Get(0) + var pErr *probe.Error + var ilmAll, ilmForce bool + var ilmID string + ilmAll = ctx.Bool("all") + ilmForce = ctx.Bool("force") + if ilmAll && ilmForce { + pErr = ilmAllRemove(objectURL) + fatalIf(pErr.Trace(objectURL), "Failed to remove all rules for `"+objectURL+"`.") + printMsg(ilmRmMessage{ + Status: "success", + ID: ilmID, + All: true, + Target: objectURL, + }) + return nil + } + if ilmID = ctx.String("id"); ilmID == "" { + fatalIf(probe.NewError(errors.New("ID not provided")), + "Failed to remove lifecycle rule") + } + pErr = ilmIDRemove(ilmID, objectURL) + fatalIf(pErr, "Failed to remove rule. ID `"+ilmID+"` Target "+objectURL+". ") + printMsg(ilmRmMessage{ + Status: "success", + ID: ilmID, + Target: objectURL, + All: false, + }) + return nil +} diff --git a/cmd/ilm/ilm-tabular-info.go b/cmd/ilm/ilm-tabular-info.go new file mode 100644 index 00000000..55502776 --- /dev/null +++ b/cmd/ilm/ilm-tabular-info.go @@ -0,0 +1,526 @@ +/* + * 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 ilm + +import ( + "encoding/xml" + "strconv" +) + +const ( + // rule ID field column width in table output + idColumnWidth int = 12 + // rule prefix field column width in table output + prefixColumnWidth int = 10 + // StatusColumnWidth column width in table output + statusColumnWidth int = 12 + // ExpiryColumnWidth column width in table output + expiryColumnWidth int = 8 + // ExpiryDatesColumnWidth column width in table output + expiryDatesColumnWidth int = 14 + // TagsColumnWidth column width in table output + tagsColumnWidth int = 18 + // TransitionColumnWidth column width in table output + transitionColumnWidth int = 14 + // TransitionDateColumnWidth column width in table output + transitionDateColumnWidth int = 18 + // 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 " + statusDisabledLabel string = "Disabled" + expiryLabel string = "Expiry" + expiryDatesLabel string = "Date/Days " + singleTagLabel string = "Tag" + tagLabel string = "Tags" + transitionLabel string = "Transition" + transitionDateLabel string = "Date/Days " + storageClassLabel string = "Storage-Class " + forceLabel string = "force" + allLabel string = "all" +) + +// Keys to be used in map structure which stores the columns to be displayed. +const ( + statusLabelKey string = "Enabled" + storageClassLabelKey string = "Storage-Class" + expiryDatesLabelKey string = "Expiry-Dates" + transitionDatesLabelKey string = "Transition-Date" + transitionDaysLabelKey string = "Transition-Days" +) + +// Some cell values +const ( + tickCell string = "\u2713 " + crossTickCell string = "\u2717 " + 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 + minimum bool +} + +// GetILMDataForShow Based on showDetails determined by user input, show the table with information. +// Table is constructed row-by-row. Headers are first, then the rest of the rows. +func GetILMDataForShow(ilmXML string, rowCheck *map[string]int, alignedHdrLabels *[]string, + cellDataNoTags *[][]string, cellDataWithTags *[][]string, tagRows *map[string][]string, + showAll, showMin, showExpiry, showTransition bool) error { + var ilmInfo LifecycleConfiguration + var err error + if ilmXML == "" { + // Empty configuration. No data to show + return nil + } + if err = xml.Unmarshal([]byte(ilmXML), &ilmInfo); err != nil { + return err + } + + // 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, + minimum: showMin, + expiry: showExpiry, + transition: showTransition, + } + getColumns(ilmInfo, *rowCheck, alignedHdrLabels, showOpts) + getILMShowDataWithoutTags(cellDataNoTags, *rowCheck, ilmInfo, showOpts) + getILMShowDataWithTags(cellDataWithTags, *tagRows, *rowCheck, ilmInfo, showOpts) + return err +} + +// 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[expiryLabel] = expiryColumnWidth + colWidth[expiryDatesLabelKey] = expiryDatesColumnWidth + colWidth[transitionLabel] = transitionColumnWidth + colWidth[transitionDatesLabelKey] = transitionDateColumnWidth + 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 + if showOpts.minimum { + return + } + 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 expiry is not set. +func getExpiryTick(rule LifecycleRule) string { + expiryTick := crossTickCell + expiryDateSet := rule.Expiration != nil && rule.Expiration.ExpirationDate != nil && !rule.Expiration.ExpirationDate.IsZero() + expirySet := rule.Expiration != nil && (expiryDateSet || rule.Expiration.ExpirationInDays > 0) + if expirySet { + expiryTick = tickCell + } + return expiryTick +} + +// The right kind of tick is returned. Cross-tick if status is 'Disabled' & tick if status is 'Enabled'. +func getStatusTick(rule LifecycleRule) 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 getExpiryDateVal(rule LifecycleRule) string { + expiryDate := blankCell + expirySet := (rule.Expiration != nil) + expiryDateSet := expirySet && rule.Expiration.ExpirationDate != nil && !rule.Expiration.ExpirationDate.IsZero() + if expiryDateSet { + expiryDate = strconv.Itoa(rule.Expiration.ExpirationDate.Day()) + " " + + rule.Expiration.ExpirationDate.Month().String()[0:3] + " " + + strconv.Itoa(rule.Expiration.ExpirationDate.Year()) + } else if expirySet && rule.Expiration.ExpirationInDays > 0 { + expiryDate = strconv.Itoa(rule.Expiration.ExpirationInDays) + " day(s)" + } + return expiryDate +} + +// Cross-tick if Transition is not set. +func getTransitionTick(rule LifecycleRule) string { + transitionSet := rule.Transition != nil + transitionDateSet := transitionSet && ((rule.Transition.TransitionDate != nil && + !rule.Transition.TransitionDate.IsZero()) || + rule.Transition.TransitionInDays > 0) + if !transitionSet || !transitionDateSet { + return crossTickCell + } + return tickCell +} + +// Transition date. 'YYYY-MM-DD'. Set for 00:00:00 GMT as per the standard. +func getTransitionDate(rule LifecycleRule) string { + transitionDate := blankCell + transitionSet := (rule.Transition != nil) + transitionDateSet := transitionSet && (rule.Transition.TransitionDate != nil && + !rule.Transition.TransitionDate.IsZero()) + transitionDaySet := transitionSet && (rule.Transition.TransitionInDays > 0) + if transitionDateSet { + transitionDate = strconv.Itoa(rule.Transition.TransitionDate.Day()) + " " + + rule.Transition.TransitionDate.Month().String()[0:3] + " " + + strconv.Itoa(rule.Transition.TransitionDate.Year()) + } else if transitionDaySet { + transitionDate = strconv.Itoa(rule.Transition.TransitionInDays) + " day(s)" + } + return transitionDate +} + +// Storage class name for transition. +func getStorageClassName(rule LifecycleRule) string { + storageClass := blankCell + transitionSet := (rule.Transition != nil) + 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 LifecycleRule) []string { + tagArr := rule.TagFilters + tagLth := len(rule.TagFilters) + if len(rule.TagFilters) == 0 && rule.RuleFilter != nil && rule.RuleFilter.And != nil { + tagLth = len(rule.RuleFilter.And.Tags) + tagArr = rule.RuleFilter.And.Tags + } + 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 += " " + } + (*rowArr)[colIdx] = getAlignedText(cellInfo.label, cellInfo.align, cellInfo.columnWidth) + } +} + +// GetILMShowDataWithoutTags - Without tags +func getILMShowDataWithoutTags(cellInfo *[][]string, rowCheck map[string]int, info LifecycleConfiguration, showOpts showDetails) { + *cellInfo = make([][]string, 0) + count := 0 + for index := 0; index < len(info.Rules); index++ { + rule := info.Rules[index] + + showExpiry := (rule.Expiration != nil) && ((rule.Expiration.ExpirationDate != nil && !rule.Expiration.ExpirationDate.IsZero()) || + rule.Expiration.ExpirationInDays > 0) + transitionSet := (rule.Transition != nil) && ((rule.Transition.TransitionDate != nil && !rule.Transition.TransitionDate.IsZero()) || + rule.Transition.TransitionInDays > 0) + skipExpTran := (showOpts.expiry && !showExpiry) || (showOpts.transition && !transitionSet) + if skipExpTran { + continue + } + tagPresent := (rule.RuleFilter != nil) && (rule.RuleFilter.And != nil) + if len(rule.TagFilters) > 0 || (tagPresent && len(rule.RuleFilter.And.Tags) > 0) { + 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: 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: getExpiryTick(rule), labelKey: expiryLabel, columnWidth: expiryColumnWidth, align: centerAlign}) + checkAddTableCell(&((*cellInfo)[count]), rowCheck, + tableCellInfo{label: getExpiryDateVal(rule), labelKey: expiryDatesLabelKey, columnWidth: expiryDatesColumnWidth, align: centerAlign}) + checkAddTableCell(&((*cellInfo)[count]), rowCheck, + tableCellInfo{label: getTransitionTick(rule), labelKey: transitionLabel, columnWidth: transitionColumnWidth, align: centerAlign}) + checkAddTableCell(&((*cellInfo)[count]), rowCheck, + tableCellInfo{label: getTransitionDate(rule), labelKey: transitionDatesLabelKey, columnWidth: transitionDateColumnWidth, align: centerAlign}) + checkAddTableCell(&((*cellInfo)[count]), rowCheck, + tableCellInfo{label: getStorageClassName(rule), labelKey: storageClassLabelKey, columnWidth: storageClassColumnWidth, 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 LifecycleConfiguration, showOpts showDetails) { + *cellInfo = make([][]string, 0) + count := 0 + for index := 0; index < len(info.Rules); index++ { + rule := info.Rules[index] + + showExpiry := (rule.Expiration != nil) && ((rule.Expiration.ExpirationDate != nil && !rule.Expiration.ExpirationDate.IsZero()) || + rule.Expiration.ExpirationInDays > 0) + transitionSet := (rule.Transition != nil) && ((rule.Transition.TransitionDate != nil && !rule.Transition.TransitionDate.IsZero()) || + rule.Transition.TransitionInDays > 0) + skipExpTran := (showOpts.expiry && !showExpiry) || (showOpts.transition && !transitionSet) + if skipExpTran { + continue + } + if len(getTagArr(rule)) == 0 { + 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: 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: getExpiryTick(rule), labelKey: expiryLabel, columnWidth: expiryColumnWidth, align: centerAlign}) + checkAddTableCell(&((*cellInfo)[count]), rowCheck, + tableCellInfo{label: getExpiryDateVal(rule), labelKey: expiryDatesLabelKey, columnWidth: expiryDatesColumnWidth, align: centerAlign}) + checkAddTableCell(&((*cellInfo)[count]), rowCheck, + tableCellInfo{label: getTransitionTick(rule), labelKey: transitionLabel, columnWidth: transitionColumnWidth, align: centerAlign}) + checkAddTableCell(&((*cellInfo)[count]), rowCheck, + tableCellInfo{label: getTransitionDate(rule), labelKey: transitionDatesLabelKey, columnWidth: transitionDateColumnWidth, align: centerAlign}) + checkAddTableCell(&((*cellInfo)[count]), rowCheck, + tableCellInfo{label: getStorageClassName(rule), labelKey: storageClassLabelKey, columnWidth: storageClassColumnWidth, 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 LifecycleRule) string { + prefixVal := "" + switch { + case rule.Prefix != "": + prefixVal = rule.Prefix + case rule.RuleFilter != nil && rule.RuleFilter.And != nil && rule.RuleFilter.And.Prefix != "": + prefixVal = rule.RuleFilter.And.Prefix + case rule.RuleFilter != nil && rule.RuleFilter.Prefix != "": + prefixVal = rule.RuleFilter.Prefix + } + return prefixVal +} + +func showExpiryDetails(rule LifecycleRule, showOpts showDetails) bool { + if showOpts.allAvailable { + return true + } + expirySet := (rule.Expiration != nil) && + ((rule.Expiration.ExpirationDate != nil && !rule.Expiration.ExpirationDate.IsZero()) || + rule.Expiration.ExpirationInDays > 0) + + return (expirySet && (showOpts.allAvailable || showOpts.expiry)) + +} + +func showExpTick(showOpts showDetails) bool { + return showOpts.allAvailable || showOpts.minimum +} + +func showTransitionTick(showOpts showDetails) bool { + return (showOpts.allAvailable || showOpts.minimum) +} + +func showTransitionDetails(rule LifecycleRule, showOpts showDetails) bool { + if showOpts.allAvailable { + return true + } + transitionSet := (rule.Transition != nil) && + ((rule.Transition.TransitionDate != nil && !rule.Transition.TransitionDate.IsZero()) || + rule.Transition.TransitionInDays > 0) + transitionDetailsShow := (showOpts.allAvailable || showOpts.transition) + return transitionSet && transitionDetailsShow +} + +func showTags(rule LifecycleRule, showOpts showDetails) bool { + if showOpts.minimum { + return false + } + tagSet := showOpts.allAvailable || + (len(rule.TagFilters) > 0 || (rule.RuleFilter != nil && rule.RuleFilter.And != nil && (len(rule.RuleFilter.And.Tags) > 0))) + return tagSet +} + +func getColumns(info LifecycleConfiguration, 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[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[expiryLabel] + if !ok && showExpTick(showOpts) { + rowCheck[expiryLabel] = incColIdx() + (*alignedHdrLabels) = append((*alignedHdrLabels), getAlignedText(expiryLabel, centerAlign, colWidthTbl[expiryLabel])) + } + _, ok = rowCheck[expiryDatesLabelKey] + if !ok && showExpiryDetails(rule, showOpts) { + rowCheck[expiryDatesLabelKey] = incColIdx() + (*alignedHdrLabels) = append((*alignedHdrLabels), getAlignedText(expiryDatesLabel, centerAlign, colWidthTbl[expiryDatesLabelKey])) + } + _, ok = rowCheck[transitionLabel] + if !ok && showTransitionTick(showOpts) { + rowCheck[transitionLabel] = incColIdx() + (*alignedHdrLabels) = append((*alignedHdrLabels), getAlignedText(transitionLabel, centerAlign, colWidthTbl[transitionLabel])) + } + _, ok = rowCheck[transitionDatesLabelKey] + if !ok && showTransitionDetails(rule, showOpts) { + rowCheck[transitionDatesLabelKey] = incColIdx() + (*alignedHdrLabels) = append((*alignedHdrLabels), getAlignedText(transitionDateLabel, centerAlign, colWidthTbl[transitionDatesLabelKey])) + } + _, ok = rowCheck[storageClassLabelKey] + if !ok && showTransitionDetails(rule, showOpts) { + rowCheck[storageClassLabelKey] = incColIdx() + (*alignedHdrLabels) = append((*alignedHdrLabels), getAlignedText(storageClassLabel, centerAlign, colWidthTbl[storageClassLabelKey])) + } + _, 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/ilm-util.go b/cmd/ilm/ilm-util.go new file mode 100644 index 00000000..64f25a78 --- /dev/null +++ b/cmd/ilm/ilm-util.go @@ -0,0 +1,420 @@ +/* + * 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 ilm + +import ( + "encoding/xml" + "errors" + "math" + "strconv" + "strings" + "time" +) + +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 +} + +func splitStr(path, sep string, n int) []string { + splits := strings.SplitN(path, sep, n) + for i := n - len(splits); i > 0; i-- { + splits = append(splits, "") + } + return splits +} + +// 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(lfcInfoXML string, ilmID string) (ilmXML string, err error) { + var lfcInfo LifecycleConfiguration + var foundIdx int + var marshalBytes []byte + + if lfcInfoXML == "" { + return "", errors.New("Rule not found") + } + if err = xml.Unmarshal([]byte(lfcInfoXML), &lfcInfo); err != nil { + return "", err + } + idx := 0 + ruleFound := false + for range lfcInfo.Rules { + rule := lfcInfo.Rules[idx] + if rule.ID == ilmID { + ruleFound = true + foundIdx = idx + break + } + idx++ + } + if !ruleFound { + ilmXML = "" + err = errors.New("Rule with id `" + ilmID + "` not found.") + } else if ruleFound && len(lfcInfo.Rules) > 1 { + lfcInfo.Rules = append(lfcInfo.Rules[:foundIdx], lfcInfo.Rules[foundIdx+1:]...) + if marshalBytes, err = xml.Marshal(lfcInfo); err == nil && ruleFound { + ilmXML = string(marshalBytes) + err = nil + } else if err != nil { + ilmXML = "" + } + } else if ruleFound && len(lfcInfo.Rules) == 1 { + ilmXML = "" + err = nil + } + return ilmXML, err + +} + +// GetILMJSON Get ILM in JSON format +func GetILMJSON(ilmXML string) (string, error) { + var err error + var ilmInfo LifecycleConfiguration + if ilmXML == "" { + return ilmXML, errors.New("Empty lifecycle configuration") + } + if err = xml.Unmarshal([]byte(ilmXML), &ilmInfo); err != nil { + return "", err + } + return ilmInfo.JSON(), nil +} + +// GetILMConfig Get ILM configuration (structure) populated with values +func GetILMConfig(ilmXML string) (ilmInfo LifecycleConfiguration, err error) { + if ilmXML == "" { + return LifecycleConfiguration{}, errors.New("Empty lifecycle configuration") + } + if err = xml.Unmarshal([]byte(ilmXML), &ilmInfo); err != nil { + return LifecycleConfiguration{}, err + } + return ilmInfo, nil +} + +func getBucketILMXML(ilm LifecycleConfiguration) (string, error) { + var err error + var cBfr []byte + if cBfr, err = xml.Marshal(ilm); err != nil { + return "", err + } + return string(cBfr), nil +} + +// Adds/Replaces a lifecycleRule in the lifecycleConfiguration structure. +// lifecycleConfiguration structure has the existing(if any) lifecycle configuration rules for the bucket. +func getILMConfigWithNewRule(lfcInfoP *LifecycleConfiguration, ilmID, ilmPrefix, ilmStatus, ilmTag, + ilmExpiryDate, ilmExpiryDays, ilmTransitionDate, ilmTransitionDays, ilmStorageClass string) (LifecycleRule, error) { + var ilmExpiry LifecycleExpiration + var ilmTransition LifecycleTransition + var err error + var newRule LifecycleRule + var ilmTagKVList []LifecycleTag + + if lfcInfoP == nil { + return LifecycleRule{}, nil + } + + if ilmTagKVList, err = extractILMTags(ilmTag); err != nil { + return LifecycleRule{}, err + } + + if ilmExpiry, err = getExpiry(ilmExpiryDate, ilmExpiryDays); err != nil { + return LifecycleRule{}, err + } + + if ilmTransition, err = getTransition(ilmStorageClass, ilmTransitionDate, ilmTransitionDays); err != nil { + return LifecycleRule{}, err + } + var andVal LifecycleAndOperator + andVal.Tags = ilmTagKVList + filter := LifecycleRuleFilter{Prefix: ilmPrefix} + if len(andVal.Tags) > 0 { + filter.And = &andVal + filter.And.Prefix = filter.Prefix + filter.Prefix = "" + } + var expP *LifecycleExpiration + var transP *LifecycleTransition + if (ilmTransition.TransitionDate != nil && + !ilmTransition.TransitionDate.IsZero()) || ilmTransition.TransitionInDays > 0 { + transP = &ilmTransition + } + if (ilmExpiry.ExpirationDate != nil && + !ilmExpiry.ExpirationDate.IsZero()) || ilmExpiry.ExpirationInDays > 0 { + expP = &ilmExpiry + } + + newRule = LifecycleRule{ + ID: ilmID, + RuleFilter: &filter, + Status: ilmStatus, + Expiration: expP, + Transition: transP, + } + if err = checkILMRule(newRule); err != nil { + return LifecycleRule{}, err + } + + idx := 0 + ruleFound := false + for range lfcInfoP.Rules { + rule := lfcInfoP.Rules[idx] + if rule.ID == ilmID { + ruleFound = true + lfcInfoP.Rules[idx] = newRule + } + idx++ + } + if !ruleFound { + lfcInfoP.Rules = append(lfcInfoP.Rules, newRule) + } + return newRule, nil +} + +// GetILMConfigToSet Get the rule in XML and set it to the object URL. +func GetILMConfigToSet(lfcInfoXML, ilmID, ilmPrefix, ilmStatus, ilmTag, + ilmExpiryDate, ilmExpiryDays, ilmTransitionDate, ilmTransitionDays, ilmStorageClass string) (string, error) { + var err error + var lfcInfo LifecycleConfiguration + var bktILM string + if err = xml.Unmarshal([]byte(lfcInfoXML), &lfcInfo); err != nil && lfcInfoXML != "" { + return "", err + } + + if _, err = getILMConfigWithNewRule(&lfcInfo, ilmID, ilmPrefix, ilmStatus, ilmTag, + ilmExpiryDate, ilmExpiryDays, ilmTransitionDate, ilmTransitionDays, ilmStorageClass); err != nil { + return "", err + } + if bktILM, err = getBucketILMXML(lfcInfo); err != nil { + return "", err + } + return bktILM, nil +} + +// Extracts the tags provided by user. The tagfilter array will be put in lifecycleRule structure. +func extractILMTags(tagLabelVal string) ([]LifecycleTag, error) { + if tagLabelVal == "" { + return nil, nil + } + var ilmTagKVList []LifecycleTag + tagValues := strings.Split(tagLabelVal, tagSeperator) + for tagIdx, tag := range tagValues { + var key, val string + if !strings.Contains(tag, keyValSeperator) { + key = tag + val = "" + } else { + key = splitStr(tag, keyValSeperator, 2)[0] + val = splitStr(tag, keyValSeperator, 2)[1] + } + if key != "" { + ilmTagKVList = append(ilmTagKVList, LifecycleTag{Key: key, Value: val}) + } else { + return nil, errors.New("Failed extracting tag argument number " + strconv.Itoa(tagIdx+1) + " " + tag + " in lifecycle configuration rule") + } + } + return ilmTagKVList, nil +} + +// Some of these rules are enforced by Amazon S3 standards. +// For example: Transition has to happen before Expiry. +// Storage class must be specified if transition date/days is provided. +func validateTranExpDate(rule LifecycleRule) error { + expirySet := (rule.Expiration != nil) + expiryDateSet := expirySet && rule.Expiration.ExpirationDate != nil && !rule.Expiration.ExpirationDate.IsZero() + expiryDaySet := expirySet && rule.Expiration.ExpirationInDays > 0 + + transitionSet := (rule.Transition != nil) + transitionDateSet := transitionSet && (rule.Transition.TransitionDate != nil && !rule.Transition.TransitionDate.IsZero()) + transitionDaySet := transitionSet && (rule.Transition.TransitionInDays > 0) + errMsg := "Error in Transition/Expiration Date/days compatibility. Transition should happen before Expiration" + if transitionDateSet && expiryDateSet { + if rule.Expiration.ExpirationDate.Before(*(rule.Transition.TransitionDate)) { + return errors.New(errMsg) + } + } + if transitionDaySet && expiryDaySet { + if rule.Transition.TransitionInDays >= rule.Expiration.ExpirationInDays { + return errors.New(errMsg) + } + } + return nil +} + +func validateTranDays(rule LifecycleRule) error { + transitionSet := (rule.Transition != nil) + transitionDaySet := transitionSet && (rule.Transition.TransitionInDays > 0) + if transitionDaySet && rule.Transition.TransitionInDays < 30 && strings.ToLower(rule.Transition.StorageClass) == "standard_ia" { + return errors.New("Transition Date/Days are less than or equal to 30 and Storage class is STANDARD_IA") + } + return nil +} + +// Amazon S3 requires a minimum of one action for a rule to be added. +func validateRuleAction(rule LifecycleRule) error { + expirySet := (rule.Expiration != nil) + transitionSet := (rule.Transition != nil) + if !expirySet && !transitionSet { + errMsg := "At least one action (Expiry or Transition) needs to be specified in a rule." + return errors.New(errMsg) + } + return nil +} + +// Check if any date is before than cur date +func validateTranExpCurdate(rule LifecycleRule) error { + var err error + expirySet := (rule.Expiration != nil) + transitionSet := (rule.Transition != nil) + transitionDateSet := transitionSet && (rule.Transition.TransitionDate != nil && !rule.Transition.TransitionDate.IsZero()) + expiryDateSet := expirySet && rule.Expiration.ExpirationDate != nil && !rule.Expiration.ExpirationDate.IsZero() + currentTime := time.Now() + curTimeStr := currentTime.Format(defaultILMDateFormat) + currentTime, err = time.Parse(defaultILMDateFormat, curTimeStr) + if err != nil { + return err + } + if expirySet && expiryDateSet && rule.Expiration.ExpirationDate.Before(currentTime) { + err = errors.New("Expiry date falls before or on today's date") + } else if transitionSet && transitionDateSet && rule.Transition.TransitionDate.Before(currentTime) { + err = errors.New("Transition date falls before or on today's date") + } + return err +} + +// Check S3 compatibility for the new rule and some other basic checks. +func checkILMRule(rule LifecycleRule) error { + var err error + + if err = validateRuleAction(rule); err != nil { + return err + } + if err = validateTranExpCurdate(rule); err != nil { + return err + } + if err = validateTranExpDate(rule); err != nil { + return err + } + if err = validateTranDays(rule); err != nil { + return err + } + return nil +} + +// Returns valid lifecycleTransition to be included in lifecycleRule +func getTransition(storageClass, transitionDateStr, transitionDayStr string) (LifecycleTransition, error) { + var transition LifecycleTransition + var err error + var transitionDate time.Time + var transitionDay int + transitionDayCheck := transitionDayStr != "" + transitionDateCheck := transitionDateStr != "" + transitionNoneCheck := (!transitionDayCheck && !transitionDateCheck && storageClass == "") + switch { + case transitionNoneCheck: + return LifecycleTransition{}, nil + case transitionDateCheck: + transitionDate, err = time.Parse(defaultILMDateFormat, transitionDateStr) + case transitionDayCheck: + if transitionDay, err = strconv.Atoi(transitionDayStr); err != nil { + return LifecycleTransition{}, err + } + } + storageClass = strings.ToUpper(storageClass) // Just-in-case the user has entered lower case characters. + transitionArgCheck := ((transitionDateStr != "" || transitionDayStr != "") && storageClass != "") + // Different kinds of compatibility checks. + switch { + case !transitionArgCheck: + return transition, errors.New("transition/storage class argument error, missing input") + case err != nil: + return LifecycleTransition{}, err + case transitionDayCheck || transitionDateCheck: + transition.StorageClass = storageClass + if transitionDayCheck { + transition.TransitionInDays = transitionDay + } else if transitionDateCheck { + transition.TransitionDate = &transitionDate + } + } + + return transition, err +} + +// Returns lifecycleExpiration to be included in lifecycleRule +func getExpiry(expiryDateStr, expiryDayStr string) (expiry LifecycleExpiration, err error) { + var expiryDate time.Time + switch { + case expiryDateStr != "": + if expiryDate, err = time.Parse(defaultILMDateFormat, expiryDateStr); err != nil || expiryDate.IsZero() { + errStr := "Error in Expiration argument " + expiryDateStr + " date conversion." + if err != nil { + errStr += err.Error() + } + err = errors.New(errStr) + } else { + expiry.ExpirationDate = &expiryDate + } + case expiryDayStr != "": + if expiry.ExpirationInDays, err = strconv.Atoi(expiryDayStr); err != nil { + errStr := "Error in Expiration argument " + expiryDayStr + ". " + err.Error() + err = errors.New(errStr) + } + } + + return expiry, err +} diff --git a/cmd/ilm/ilm.go b/cmd/ilm/ilm.go new file mode 100644 index 00000000..f9c80f65 --- /dev/null +++ b/cmd/ilm/ilm.go @@ -0,0 +1,109 @@ +/* + * 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 ilm contains all the ilm related functionality. TO BE ACCESSED VIA GET FUNCTIONS or Operation-related Global functions. +package ilm + +import ( + "encoding/json" + "encoding/xml" + "time" + + "github.com/minio/minio/pkg/console" +) + +// AbortIncompleteMultipartUpload structure +type AbortIncompleteMultipartUpload struct { + XMLName xml.Name `xml:"AbortIncompleteMultipartUpload,omitempty" json:"-"` + DaysAfterInitiation int64 `xml:"DaysAfterInitiation,omitempty" json:"DaysAfterInitiation,omitempty"` +} + +// NoncurrentVersionTransition structure +type NoncurrentVersionTransition struct { + XMLName xml.Name `xml:"NoncurrentVersionTransition,omitempty" json:"-"` + StorageClass string `xml:"StorageClass,omitempty" json:"StorageClass,omitempty"` + TransitionInDays int `xml:"TransitionInDays,omitempty" json:"TransitionInDays,omitempty"` +} + +// LifecycleTag structure key/value pair representing an object tag to apply lifecycle configuration +type LifecycleTag struct { + XMLName xml.Name `xml:"Tag,omitempty" json:"-"` + Key string `xml:"Key,omitempty" json:"Key,omitempty"` + Value string `xml:"Value,omitempty" json:"Value,omitempty"` +} + +// LifecycleTransition structure - transition details of lifeycle configuration +type LifecycleTransition struct { + XMLName xml.Name `xml:"Transition" json:"-"` + TransitionDate *time.Time `xml:"Date,omitempty" json:"Date,omitempty"` + StorageClass string `xml:"StorageClass,omitempty" json:"StorageClass,omitempty"` + TransitionInDays int `xml:"Days,omitempty" json:"Days,omitempty"` +} + +// LifecycleAndOperator And Rule for LifecycleTag, to be used in LifecycleRuleFilter +type LifecycleAndOperator struct { + XMLName xml.Name `xml:"And,omitempty" json:"-"` + Prefix string `xml:"Prefix,omitempty" json:"Prefix,omitempty"` + Tags []LifecycleTag `xml:"Tag,omitempty" json:"Tags,omitempty"` +} + +// LifecycleRuleFilter will be used in selecting rule(s) for lifecycle configuration +type LifecycleRuleFilter struct { + XMLName xml.Name `xml:"Filter" json:"-"` + And *LifecycleAndOperator `xml:"And,omitempty" json:"And,omitempty"` + Prefix string `xml:"Prefix,omitempty" json:"Prefix,omitempty"` + Tag *LifecycleTag `xml:"Tag,omitempty" json:"-"` +} + +// LifecycleExpiration structure - expiration details of lifeycle configuration +type LifecycleExpiration struct { + XMLName xml.Name `xml:"Expiration,omitempty" json:"-"` + ExpirationDate *time.Time `xml:"Date,omitempty" json:"Date,omitempty"` + ExpirationInDays int `xml:"Days,omitempty" json:"Days,omitempty"` +} + +// LifecycleRule represents a single rule in lifecycle configuration +type LifecycleRule struct { + XMLName xml.Name `xml:"Rule,omitempty" json:"-"` + AbortIncompleteMultipartUpload *AbortIncompleteMultipartUpload `xml:"AbortIncompleteMultipartUpload,omitempty" json:"AbortIncompleteMultipartUpload,omitempty"` + Expiration *LifecycleExpiration `xml:"Expiration,omitempty" json:"Expiration,omitempty"` + ID string `xml:"ID" json:"ID"` + RuleFilter *LifecycleRuleFilter `xml:"Filter,omitempty" json:"Filter,omitempty"` + NoncurrentVersionTransition *NoncurrentVersionTransition `xml:"NoncurrentVersionTransition,omitempty" json:"NoncurrentVersionTransition,omitempty"` + NoncurrentVersionTransitions []NoncurrentVersionTransition `xml:"NoncurrentVersionTransitions,omitempty" json:"NoncurrentVersionTransitions,omitempty"` + Prefix string `xml:"Prefix,omitempty" json:"Prefix,omitempty"` + Status string `xml:"Status" json:"Status"` + Transition *LifecycleTransition `xml:"Transition,omitempty" json:"Transition,omitempty"` + Transitions []LifecycleTransition `xml:"Transitions,omitempty" json:"Transitions,omitempty"` + TagFilters []LifecycleTag `xml:"Tag,omitempty" json:"Tags,omitempty"` +} + +// LifecycleConfiguration is a collection of LifecycleRule objects. +type LifecycleConfiguration struct { + XMLName xml.Name `xml:"LifecycleConfiguration,omitempty" json:"-"` + Rules []LifecycleRule `xml:"Rule"` +} + +// JSON jsonified lifecycle configuration. +func (l LifecycleConfiguration) JSON() string { + var ilmJSONbytes []byte + var err error + ilmJSONbytes, err = json.MarshalIndent(l, "", " ") + if err != nil { + console.Fatal("Failed to get lifecycle configuration in JSON format.") + } + return string(ilmJSONbytes) +} diff --git a/cmd/main.go b/cmd/main.go index e1b480a6..b956ccc2 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -334,6 +334,7 @@ var appCmds = []cli.Command{ diffCmd, rmCmd, eventCmd, + ilmCmd, watchCmd, policyCmd, tagCmd,