diff --git a/cmd/client-fs.go b/cmd/client-fs.go index d14b88ef..53a1063f 100644 --- a/cmd/client-fs.go +++ b/cmd/client-fs.go @@ -1038,6 +1038,11 @@ func (f *fsClient) GetAccessRules() (map[string]string, *probe.Error) { }) } +// Set object retention for a given object. +func (f *fsClient) PutObjectRetention(path string, mode *minio.RetentionMode, validity *uint, unit *minio.ValidityUnit) *probe.Error { + return probe.NewError(APINotImplemented{API: "PutObjectRetention", APIType: "filesystem"}) +} + // GetAccess - get access policy permissions. func (f *fsClient) GetAccess() (access string, policyJSON string, err *probe.Error) { // For windows this feature is not implemented. diff --git a/cmd/client-s3.go b/cmd/client-s3.go index b681e665..b841d0ad 100644 --- a/cmd/client-s3.go +++ b/cmd/client-s3.go @@ -2075,6 +2075,35 @@ func (c *s3Client) SetObjectLockConfig(mode *minio.RetentionMode, validity *uint return nil } +// Set object retention for a given object. +func (c *s3Client) PutObjectRetention(path string, mode *minio.RetentionMode, validity *uint, unit *minio.ValidityUnit) *probe.Error { + bucket, object := c.splitPath(path) + t := UTCNow() + if *unit == minio.Years { + t = t.AddDate(int(*validity), 0, 0) + } else { + t = t.AddDate(0, 0, int(*validity)) + } + timeStr := t.Format(time.RFC3339) + + t1, e := time.Parse( + time.RFC3339, + timeStr) + if e != nil { + return probe.NewError(e) + } + opts := minio.PutObjectRetentionOptions{ + RetainUntilDate: &t1, + Mode: mode, + } + err := c.api.PutObjectRetention(bucket, object, opts) + if err != nil { + return probe.NewError(err) + } + + return nil +} + // Get object lock configuration of bucket. func (c *s3Client) GetObjectLockConfig() (mode *minio.RetentionMode, validity *uint, unit *minio.ValidityUnit, perr *probe.Error) { bucket, _ := c.url2BucketAndObject() diff --git a/cmd/client.go b/cmd/client.go index 37cc1768..2edf6da3 100644 --- a/cmd/client.go +++ b/cmd/client.go @@ -68,6 +68,10 @@ type Client interface { Get(sse encrypt.ServerSide) (reader io.ReadCloser, err *probe.Error) Put(ctx context.Context, reader io.Reader, size int64, metadata map[string]string, progress io.Reader, sse encrypt.ServerSide) (n int64, err *probe.Error) PutRetention(ctx context.Context, metadata map[string]string) *probe.Error + + // Object Locking related API + PutObjectRetention(path string, mode *minio.RetentionMode, validity *uint, unit *minio.ValidityUnit) *probe.Error + // I/O operations with expiration ShareDownload(expires time.Duration) (string, *probe.Error) ShareUpload(bool, time.Duration, string) (string, map[string]string, *probe.Error) diff --git a/cmd/lock-main.go b/cmd/lock-main.go index 327f95f3..a9cbab69 100644 --- a/cmd/lock-main.go +++ b/cmd/lock-main.go @@ -20,6 +20,7 @@ import ( "errors" "fmt" "strconv" + "strings" "github.com/fatih/color" "github.com/minio/cli" @@ -48,7 +49,7 @@ var lockCmd = cli.Command{ {{.HelpName}} - {{.Usage}} USAGE: - {{.HelpName}} [FLAGS] TARGET [GOVERNANCE | COMPLIANCE] [VALIDITY] + {{.HelpName}} [FLAGS] TARGET [governance | compliance] [VALIDITY] FLAGS: {{range .VisibleFlags}}{{.}} @@ -58,7 +59,7 @@ VALIDITY: EXAMPLES: 1. Set object lock configuration - $ {{.HelpName}} myminio/mybucket GOVERNANCE 30d + $ {{.HelpName}} myminio/mybucket compliance 30d 2. Get object lock configuration $ {{.HelpName}} myminio/mybucket @@ -164,7 +165,7 @@ func mainLock(ctx *cli.Context) error { fatalIf(probe.NewError(errors.New("invalid argument")), "clear flag must be passed with target alone") } - m := minio.RetentionMode(args[1]) + m := minio.RetentionMode(strings.ToUpper(args[1])) if !m.IsValid() { fatalIf(probe.NewError(errors.New("invalid argument")), "invalid retention mode '%v'", m) } diff --git a/cmd/main.go b/cmd/main.go index d795f0f3..2183eaf9 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -323,6 +323,7 @@ var appCmds = []cli.Command{ treeCmd, duCmd, lockCmd, + retentionCmd, diffCmd, rmCmd, eventCmd, diff --git a/cmd/retention-main.go b/cmd/retention-main.go new file mode 100644 index 00000000..76c07a38 --- /dev/null +++ b/cmd/retention-main.go @@ -0,0 +1,199 @@ +/* + * MinIO Client (C) 2019 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/json" + "errors" + "fmt" + "strconv" + "strings" + + "github.com/fatih/color" + "github.com/minio/cli" + "github.com/minio/mc/pkg/console" + "github.com/minio/mc/pkg/probe" + minio "github.com/minio/minio-go/v6" +) + +var retentionCmd = cli.Command{ + Name: "retention", + Usage: "set object retention for objects with a given prefix", + Action: mainRetention, + Before: setGlobalsFromContext, + Flags: globalFlags, + CustomHelpTemplate: `NAME: + {{.HelpName}} - {{.Usage}} + +USAGE: + {{.HelpName}} [FLAGS] TARGET [governance | compliance] [VALIDITY] + +FLAGS: + {{range .VisibleFlags}}{{.}} + {{end}} +VALIDITY: + This argument must be formatted like Nd or Ny where 'd' denotes days and 'y' denotes years e.g. 10d, 3y. + +EXAMPLES: + 1. Set object retention for objects in a given prefix + $ {{.HelpName}} myminio/mybucket/prefix compliance 30d +`, +} + +// Structured message depending on the type of console. +type retentionCmdMessage struct { + Mode minio.RetentionMode `json:"mode"` + Validity *string `json:"validity"` + URLPath string `json:"urlpath"` + Status string `json:"status"` + Err error `json:"error"` +} + +// Colorized message for console printing. +func (m retentionCmdMessage) String() string { + if m.Err != nil { + return console.Colorize("RetentionMessageFailure", "Cannot set object retention on `"+m.URLPath+"`."+m.Err.Error()) + } + return "" +} + +// JSON'ified message for scripting. +func (m retentionCmdMessage) JSON() string { + msgBytes, e := json.MarshalIndent(m, "", " ") + fatalIf(probe.NewError(e), "Unable to marshal into JSON.") + return string(msgBytes) +} + +// setRetention - Set Retention for all objects within a given prefix. +func setRetention(urlStr string, mode *minio.RetentionMode, validity *uint, unit *minio.ValidityUnit) error { + clnt, err := newClient(urlStr) + if err != nil { + fatalIf(err.Trace(), "Cannot parse the provided url.") + } + + validityStr := func() *string { + if validity == nil { + return nil + } + + unitStr := "d" + if *unit == minio.Years { + unitStr = "y" + } + s := fmt.Sprint(*validity, unitStr) + return &s + } + + var cErr error + errorsFound := false + for content := range clnt.List(true, false, false, DirNone) { + if content.Err != nil { + errorIf(content.Err.Trace(clnt.GetURL().String()), "Unable to list folder.") + cErr = exitStatus(globalErrorExitStatus) // Set the exit status. + continue + } + probeErr := clnt.PutObjectRetention(content.URL.Path, mode, validity, unit) + if probeErr != nil { + errorsFound = true + printMsg(retentionCmdMessage{ + Mode: *mode, + Validity: validityStr(), + Status: "failure", + URLPath: content.URL.Path, + Err: probeErr.ToGoError(), + }) + } else { + if globalJSON { + printMsg(retentionCmdMessage{ + Mode: *mode, + Validity: validityStr(), + Status: "success", + URLPath: content.URL.Path, + }) + } + } + } + if cErr == nil && !globalJSON { + if errorsFound { + console.Print(console.Colorize("RetentionPartialFailure", fmt.Sprintf("Errors found while setting retention on objects with prefix `%s`.\n", urlStr))) + } else { + console.Print(console.Colorize("RetentionSuccess", fmt.Sprintf("Object retention successfully set for prefix `%s`.\n", urlStr))) + } + } + return cErr +} + +// main for retention command. +func mainRetention(ctx *cli.Context) error { + console.SetColor("RetentionSuccess", color.New(color.FgGreen, color.Bold)) + console.SetColor("RetentionPartialFailure", color.New(color.FgRed, color.Bold)) + console.SetColor("RetentionMessageFailure", color.New(color.FgYellow)) + + // Parse encryption keys per command. + _, err := getEncKeys(ctx) + fatalIf(err, "Unable to parse encryption keys.") + + // lock specific flags. + clearLock := ctx.Bool("clear") + + args := ctx.Args() + + var urlStr string + var mode *minio.RetentionMode + var validity *uint + var unit *minio.ValidityUnit + + switch l := len(args); l { + case 3: + urlStr = args[0] + if clearLock { + fatalIf(probe.NewError(errors.New("invalid argument")), "clear flag must be passed with target alone") + } + + m := minio.RetentionMode(strings.ToUpper(args[1])) + if !m.IsValid() { + fatalIf(probe.NewError(errors.New("invalid argument")), "invalid retention mode '%v'", m) + } + + mode = &m + + validityStr := args[2] + unitStr := string(validityStr[len(validityStr)-1]) + + validityStr = validityStr[:len(validityStr)-1] + ui64, err := strconv.ParseUint(validityStr, 10, 64) + if err != nil { + fatalIf(probe.NewError(errors.New("invalid argument")), "invalid validity '%v'", args[2]) + } + u := uint(ui64) + validity = &u + + switch unitStr { + case "d", "D": + d := minio.Days + unit = &d + case "y", "Y": + y := minio.Years + unit = &y + default: + fatalIf(probe.NewError(errors.New("invalid argument")), "invalid validity format '%v'", args[2]) + } + default: + cli.ShowCommandHelpAndExit(ctx, "retention", 1) + } + return setRetention(urlStr, mode, validity, unit) +}