retention: Refactor and add support of versioning (#3347)
This commit is contained in:
@@ -1,176 +0,0 @@
|
||||
/*
|
||||
* MinIO Client (C) 2019-2020 MinIO, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
json "github.com/minio/mc/pkg/colorjson"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
minio "github.com/minio/minio-go/v7"
|
||||
"github.com/minio/minio/pkg/console"
|
||||
)
|
||||
|
||||
var bucketLockCmd = cli.Command{
|
||||
Name: "lock",
|
||||
Usage: "manage default bucket object lock configuration",
|
||||
Action: mainLock,
|
||||
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 lock configuration
|
||||
$ {{.HelpName}} myminio/mybucket compliance 30d
|
||||
|
||||
2. Get object lock configuration
|
||||
$ {{.HelpName}} myminio/mybucket info
|
||||
|
||||
3. Clear object lock configuration
|
||||
$ {{.HelpName}} myminio/mybucket clear
|
||||
`,
|
||||
}
|
||||
|
||||
// Structured message depending on the type of console.
|
||||
type lockCmdMessage struct {
|
||||
Enabled string `json:"enabled"`
|
||||
Mode minio.RetentionMode `json:"mode"`
|
||||
Validity string `json:"validity"`
|
||||
Status string `json:"status"`
|
||||
}
|
||||
|
||||
// Colorized message for console printing.
|
||||
func (m lockCmdMessage) String() string {
|
||||
if m.Mode == "" {
|
||||
return console.Colorize("Clear", "Object lock configuration cleared successfully")
|
||||
}
|
||||
|
||||
return fmt.Sprintf("%s mode is enabled for %s", console.Colorize("Mode", m.Mode), console.Colorize("Validity", m.Validity))
|
||||
}
|
||||
|
||||
// JSON'ified message for scripting.
|
||||
func (m lockCmdMessage) JSON() string {
|
||||
msgBytes, e := json.MarshalIndent(m, "", " ")
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
return string(msgBytes)
|
||||
}
|
||||
|
||||
// lock - set/get object lock configuration.
|
||||
func lock(urlStr string, mode minio.RetentionMode, validity uint64, unit minio.ValidityUnit, op string) error {
|
||||
client, err := newClient(urlStr)
|
||||
if err != nil {
|
||||
fatalIf(err.Trace(), "Unable to parse the provided url.")
|
||||
}
|
||||
|
||||
ctx, cancelLock := context.WithCancel(globalContext)
|
||||
defer cancelLock()
|
||||
if op == "clear" || mode != "" {
|
||||
err = client.SetObjectLockConfig(ctx, mode, validity, unit)
|
||||
fatalIf(err, "Unable to enable object lock configuration on the specified bucket.")
|
||||
} else {
|
||||
_, mode, validity, unit, err = client.GetObjectLockConfig(ctx)
|
||||
fatalIf(err, "Unable to get object lock configuration on the specified bucket.")
|
||||
}
|
||||
|
||||
printMsg(lockCmdMessage{
|
||||
Enabled: "Enabled",
|
||||
Mode: mode,
|
||||
Validity: fmt.Sprintf("%d%s", validity, unit),
|
||||
Status: "success",
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func parseRetentionValidity(validityStr string, m minio.RetentionMode) (uint64, minio.ValidityUnit, *probe.Error) {
|
||||
if !m.IsValid() {
|
||||
return 0, "", errInvalidArgument().Trace(fmt.Sprintf("invalid retention mode '%v'", m))
|
||||
}
|
||||
|
||||
unitStr := string(validityStr[len(validityStr)-1])
|
||||
validityStr = validityStr[:len(validityStr)-1]
|
||||
validity, e := strconv.ParseUint(validityStr, 10, 64)
|
||||
if e != nil {
|
||||
return 0, "", probe.NewError(e).Trace(validityStr)
|
||||
}
|
||||
|
||||
var unit minio.ValidityUnit
|
||||
switch unitStr {
|
||||
case "d", "D":
|
||||
unit = minio.Days
|
||||
case "y", "Y":
|
||||
unit = minio.Years
|
||||
default:
|
||||
return 0, "", errInvalidArgument().Trace(unitStr)
|
||||
}
|
||||
|
||||
return validity, unit, nil
|
||||
}
|
||||
|
||||
// main for lock command.
|
||||
func mainLock(ctx *cli.Context) error {
|
||||
console.SetColor("Mode", color.New(color.FgCyan, color.Bold))
|
||||
console.SetColor("Validity", color.New(color.FgYellow))
|
||||
console.SetColor("Clear", color.New(color.FgGreen))
|
||||
args := ctx.Args()
|
||||
|
||||
var urlStr string
|
||||
var mode minio.RetentionMode
|
||||
var validity uint64
|
||||
var unit minio.ValidityUnit
|
||||
var err *probe.Error
|
||||
var op string
|
||||
switch l := len(args); l {
|
||||
case 2:
|
||||
urlStr = args[0]
|
||||
switch args[1] {
|
||||
case "info":
|
||||
op = "info"
|
||||
case "clear":
|
||||
op = "clear"
|
||||
default:
|
||||
fatalIf(err.Trace(args...), "unable to parse input arguments")
|
||||
}
|
||||
case 3:
|
||||
op = "set"
|
||||
urlStr = args[0]
|
||||
mode = minio.RetentionMode(strings.ToUpper(args[1]))
|
||||
validity, unit, err = parseRetentionValidity(args[2], mode)
|
||||
if err != nil {
|
||||
fatalIf(err.Trace(args...), "unable to parse input arguments")
|
||||
}
|
||||
default:
|
||||
cli.ShowCommandHelpAndExit(ctx, "lock", 1)
|
||||
}
|
||||
|
||||
return lock(urlStr, mode, validity, unit, op)
|
||||
}
|
||||
+8
-1
@@ -942,13 +942,20 @@ func (f *fsClient) GetAccessRules(ctx context.Context) (map[string]string, *prob
|
||||
}
|
||||
|
||||
// Set object retention for a given object.
|
||||
func (f *fsClient) PutObjectRetention(ctx context.Context, mode minio.RetentionMode, retainUntilDate time.Time, bypassGovernance bool) *probe.Error {
|
||||
func (f *fsClient) PutObjectRetention(ctx context.Context, versionID string, mode minio.RetentionMode, retainUntilDate time.Time, bypassGovernance bool) *probe.Error {
|
||||
return probe.NewError(APINotImplemented{
|
||||
API: "PutObjectRetention",
|
||||
APIType: "filesystem",
|
||||
})
|
||||
}
|
||||
|
||||
func (f *fsClient) GetObjectRetention(ctx context.Context, versionID string) (minio.RetentionMode, time.Time, *probe.Error) {
|
||||
return "", time.Time{}, probe.NewError(APINotImplemented{
|
||||
API: "GetObjectRetention",
|
||||
APIType: "filesystem",
|
||||
})
|
||||
}
|
||||
|
||||
// Set object legal hold for a given object.
|
||||
func (f *fsClient) PutObjectLegalHold(ctx context.Context, versionID string, lhold minio.LegalHoldStatus) *probe.Error {
|
||||
return probe.NewError(APINotImplemented{
|
||||
|
||||
+47
-16
@@ -2284,23 +2284,54 @@ func (c *S3Client) SetObjectLockConfig(ctx context.Context, mode minio.Retention
|
||||
}
|
||||
|
||||
// PutObjectRetention - Set object retention for a given object.
|
||||
func (c *S3Client) PutObjectRetention(ctx context.Context, mode minio.RetentionMode, retainUntilDate time.Time, bypassGovernance bool) *probe.Error {
|
||||
func (c *S3Client) PutObjectRetention(ctx context.Context, versionID string, mode minio.RetentionMode, retainUntilDate time.Time, bypassGovernance bool) *probe.Error {
|
||||
bucket, object := c.url2BucketAndObject()
|
||||
|
||||
if mode != "" && !retainUntilDate.IsZero() {
|
||||
opts := minio.PutObjectRetentionOptions{
|
||||
RetainUntilDate: &retainUntilDate,
|
||||
Mode: &mode,
|
||||
GovernanceBypass: bypassGovernance,
|
||||
}
|
||||
e := c.api.PutObjectRetention(ctx, bucket, object, opts)
|
||||
if e != nil {
|
||||
return probe.NewError(e).Trace(c.GetURL().String())
|
||||
}
|
||||
return nil
|
||||
var (
|
||||
modePtr *minio.RetentionMode
|
||||
retainUntilDatePtr *time.Time
|
||||
)
|
||||
|
||||
if mode != "" && retainUntilDate.IsZero() {
|
||||
return errInvalidArgument().Trace(c.GetURL().String())
|
||||
}
|
||||
|
||||
return errInvalidArgument().Trace(c.GetURL().String())
|
||||
if mode != "" {
|
||||
modePtr = &mode
|
||||
retainUntilDatePtr = &retainUntilDate
|
||||
}
|
||||
|
||||
opts := minio.PutObjectRetentionOptions{
|
||||
VersionID: versionID,
|
||||
RetainUntilDate: retainUntilDatePtr,
|
||||
Mode: modePtr,
|
||||
GovernanceBypass: bypassGovernance,
|
||||
}
|
||||
e := c.api.PutObjectRetention(ctx, bucket, object, opts)
|
||||
if e != nil {
|
||||
return probe.NewError(e).Trace(c.GetURL().String())
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetObjectRetention - Get object retention for a given object.
|
||||
func (c *S3Client) GetObjectRetention(ctx context.Context, versionID string) (minio.RetentionMode, time.Time, *probe.Error) {
|
||||
bucket, object := c.url2BucketAndObject()
|
||||
modePtr, untilPtr, e := c.api.GetObjectRetention(ctx, bucket, object, versionID)
|
||||
if e != nil {
|
||||
return "", time.Time{}, probe.NewError(e).Trace(c.GetURL().String())
|
||||
}
|
||||
var (
|
||||
mode minio.RetentionMode
|
||||
until time.Time
|
||||
)
|
||||
if modePtr != nil {
|
||||
mode = *modePtr
|
||||
}
|
||||
if untilPtr != nil {
|
||||
until = *untilPtr
|
||||
}
|
||||
return mode, until, nil
|
||||
}
|
||||
|
||||
// PutObjectLegalHold - Set object legal hold for a given object.
|
||||
@@ -2346,7 +2377,7 @@ func (c *S3Client) GetObjectLegalHold(ctx context.Context, versionID string) (mi
|
||||
func (c *S3Client) GetObjectLockConfig(ctx context.Context) (string, minio.RetentionMode, uint64, minio.ValidityUnit, *probe.Error) {
|
||||
bucket, _ := c.url2BucketAndObject()
|
||||
|
||||
enabled, mode, validity, unit, e := c.api.GetObjectLockConfig(ctx, bucket)
|
||||
status, mode, validity, unit, e := c.api.GetObjectLockConfig(ctx, bucket)
|
||||
if e != nil {
|
||||
return "", "", 0, "", probe.NewError(e).Trace(c.GetURL().String())
|
||||
}
|
||||
@@ -2354,10 +2385,10 @@ func (c *S3Client) GetObjectLockConfig(ctx context.Context) (string, minio.Reten
|
||||
if mode != nil && validity != nil && unit != nil {
|
||||
// FIXME: this is too ugly, fix minio-go
|
||||
vuint64 := uint64(*validity)
|
||||
return enabled, *mode, vuint64, *unit, nil
|
||||
return status, *mode, vuint64, *unit, nil
|
||||
}
|
||||
|
||||
return enabled, "", 0, "", nil
|
||||
return status, "", 0, "", nil
|
||||
}
|
||||
|
||||
// GetTags - Get tags of bucket or object.
|
||||
|
||||
+2
-1
@@ -110,7 +110,8 @@ type Client interface {
|
||||
Put(ctx context.Context, reader io.Reader, size int64, metadata map[string]string, progress io.Reader, sse encrypt.ServerSide, md5, disableMultipart, isPreserve bool) (n int64, err *probe.Error)
|
||||
|
||||
// Object Locking related API
|
||||
PutObjectRetention(ctx context.Context, mode minio.RetentionMode, retainUntilDate time.Time, bypassGovernance bool) *probe.Error
|
||||
PutObjectRetention(ctx context.Context, versionID string, mode minio.RetentionMode, retainUntilDate time.Time, bypassGovernance bool) *probe.Error
|
||||
GetObjectRetention(ctx context.Context, versionID string) (minio.RetentionMode, time.Time, *probe.Error)
|
||||
PutObjectLegalHold(ctx context.Context, versionID string, hold minio.LegalHoldStatus) *probe.Error
|
||||
GetObjectLegalHold(ctx context.Context, versionID string) (minio.LegalHoldStatus, *probe.Error)
|
||||
|
||||
|
||||
@@ -297,7 +297,7 @@ func putTargetRetention(ctx context.Context, alias string, urlStr string, metada
|
||||
retainUntilDate = t.UTC()
|
||||
}
|
||||
}
|
||||
if err := targetClnt.PutObjectRetention(ctx, lockMode, retainUntilDate, false); err != nil {
|
||||
if err := targetClnt.PutObjectRetention(ctx, "", lockMode, retainUntilDate, false); err != nil {
|
||||
return err.Trace(alias, urlStr)
|
||||
}
|
||||
return nil
|
||||
@@ -432,10 +432,13 @@ func uploadSourceToTargetURL(ctx context.Context, urls URLs, progress io.Reader,
|
||||
// for the most part source metadata is copied over.
|
||||
if urls.TargetContent.RetentionEnabled {
|
||||
m := minio.RetentionMode(strings.ToUpper(urls.TargetContent.RetentionMode))
|
||||
if !m.IsValid() {
|
||||
return urls.WithError(probe.NewError(errors.New("invalid retention mode")).Trace(targetURL.String()))
|
||||
}
|
||||
|
||||
var dur uint64
|
||||
var unit minio.ValidityUnit
|
||||
dur, unit, err = parseRetentionValidity(urls.TargetContent.RetentionDuration, m)
|
||||
dur, unit, err = parseRetentionValidity(urls.TargetContent.RetentionDuration)
|
||||
if err != nil {
|
||||
return urls.WithError(err.Trace(targetURL.String()))
|
||||
}
|
||||
|
||||
@@ -340,7 +340,6 @@ var appCmds = []cli.Command{
|
||||
diffCmd,
|
||||
rmCmd,
|
||||
versionCmd,
|
||||
bucketLockCmd,
|
||||
bucketILMCmd,
|
||||
encryptCmd,
|
||||
eventCmd,
|
||||
|
||||
+2
-3
@@ -18,7 +18,6 @@ package cmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"sync"
|
||||
@@ -294,7 +293,7 @@ func mainMove(cliCtx *cli.Context) error {
|
||||
srcURL := args.Get(0)
|
||||
dstURL := args.Get(1)
|
||||
if srcURL == dstURL {
|
||||
fatalIf(probe.NewError(errors.New("")), fmt.Sprintf("Source and destination urls cannot be the same: %v.", srcURL))
|
||||
fatalIf(errDummy().Trace(), fmt.Sprintf("Source and destination urls cannot be the same: %v.", srcURL))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -306,7 +305,7 @@ func mainMove(cliCtx *cli.Context) error {
|
||||
|
||||
if s3Client, ok := client.(*S3Client); ok {
|
||||
if _, _, _, _, err = s3Client.GetObjectLockConfig(ctx); err == nil {
|
||||
fatalIf(probe.NewError(errors.New("")), fmt.Sprintf("Object lock configuration is enabled on the specified bucket in alias %v.", urlStr))
|
||||
fatalIf(errDummy().Trace(), fmt.Sprintf("Object lock configuration is enabled on the specified bucket in alias %v.", urlStr))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
/*
|
||||
* MinIO Client (C) 2019-2020 MinIO, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/minio-go/v7"
|
||||
"github.com/minio/minio/pkg/console"
|
||||
)
|
||||
|
||||
var (
|
||||
retentionClearFlags = []cli.Flag{
|
||||
cli.BoolFlag{
|
||||
Name: "recursive, r",
|
||||
Usage: "clear retention recursively",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "version-id, vid",
|
||||
Usage: "clear retention of a specific object version",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "rewind",
|
||||
Usage: "roll back object(s) to current version at specified time",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "versions",
|
||||
Usage: "clear retention of object(s) and all its versions",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "default",
|
||||
Usage: "set default bucket locking",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
var retentionClearCmd = cli.Command{
|
||||
Name: "clear",
|
||||
Usage: "clear retention for object(s)",
|
||||
Action: mainRetentionClear,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: append(retentionClearFlags, globalFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} [FLAGS] TARGET
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
|
||||
EXAMPLES:
|
||||
1. Clear object retention for a specific object
|
||||
$ {{.HelpName}} myminio/mybucket/prefix/obj.csv
|
||||
|
||||
2. Clear object retention for recursively for all objects at a given prefix
|
||||
$ {{.HelpName}} myminio/mybucket/prefix --recursive
|
||||
|
||||
3. Clear object retention for a specific version of a specific object
|
||||
$ {{.HelpName}} myminio/mybucket/prefix/obj.csv --version-id "3Jr2x6fqlBUsVzbvPihBO3HgNpgZgAnp"
|
||||
|
||||
4. Clear object retention for recursively for all versions of all objects
|
||||
$ {{.HelpName}} myminio/mybucket/prefix --recursive --versions
|
||||
|
||||
5. Clear object retention for recursively for all versions created one year ago
|
||||
$ {{.HelpName}} myminio/mybucket/prefix --recursive --versions --rewind 365d
|
||||
|
||||
6. Clear a bucket retention configuration
|
||||
$ {{.HelpName}} --default myminio/mybucket/
|
||||
`,
|
||||
}
|
||||
|
||||
func parseClearRetentionArgs(cliCtx *cli.Context) (target, versionID string, timeRef time.Time, withVersions, recursive, bucketMode bool) {
|
||||
args := cliCtx.Args()
|
||||
target = args[0]
|
||||
if target == "" {
|
||||
fatalIf(errInvalidArgument().Trace(), "invalid target url '%v'", target)
|
||||
}
|
||||
|
||||
versionID = cliCtx.String("version-id")
|
||||
timeRef = parseRewindFlag(cliCtx.String("rewind"))
|
||||
withVersions = cliCtx.Bool("versions")
|
||||
recursive = cliCtx.Bool("recursive")
|
||||
bucketMode = cliCtx.Bool("default")
|
||||
return
|
||||
}
|
||||
|
||||
// Clear Retention for one object/version or many objects within a given prefix, bypass governance is always enabled
|
||||
func clearRetention(ctx context.Context, target, versionID string, timeRef time.Time, withOlderVersions, isRecursive bool) error {
|
||||
return applyRetention(ctx, "clear", target, versionID, timeRef, withOlderVersions, isRecursive, "", 0, minio.Days, true)
|
||||
}
|
||||
|
||||
func clearBucketLock(urlStr string) error {
|
||||
return applyBucketLock("clear", urlStr, "", 0, "")
|
||||
}
|
||||
|
||||
// main for retention clear command.
|
||||
func mainRetentionClear(cliCtx *cli.Context) error {
|
||||
ctx, cancelSetRetention := context.WithCancel(globalContext)
|
||||
defer cancelSetRetention()
|
||||
|
||||
console.SetColor("RetentionSuccess", color.New(color.FgGreen, color.Bold))
|
||||
console.SetColor("RetentionFailure", color.New(color.FgYellow))
|
||||
|
||||
if len(cliCtx.Args()) != 1 {
|
||||
cli.ShowCommandHelpAndExit(cliCtx, "clear", 1)
|
||||
}
|
||||
|
||||
target, versionID, rewind, withVersions, recursive, bucketMode := parseClearRetentionArgs(cliCtx)
|
||||
|
||||
checkObjectLockSupport(ctx, target)
|
||||
|
||||
if bucketMode {
|
||||
return clearBucketLock(target)
|
||||
}
|
||||
|
||||
if withVersions && rewind.IsZero() {
|
||||
rewind = time.Now().UTC()
|
||||
}
|
||||
|
||||
return clearRetention(ctx, target, versionID, rewind, withVersions, recursive)
|
||||
}
|
||||
@@ -0,0 +1,304 @@
|
||||
/*
|
||||
* MinIO Client (C) 2019-2020 MinIO, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
json "github.com/minio/mc/pkg/colorjson"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/minio-go/v7"
|
||||
"github.com/minio/minio/pkg/console"
|
||||
)
|
||||
|
||||
// Structured message depending on the type of console.
|
||||
type retentionCmdMessage struct {
|
||||
Op string `json:"op"`
|
||||
Mode minio.RetentionMode `json:"mode"`
|
||||
Validity string `json:"validity"`
|
||||
URLPath string `json:"urlpath"`
|
||||
VersionID string `json:"versionID"`
|
||||
Status string `json:"status"`
|
||||
Err error `json:"error"`
|
||||
}
|
||||
|
||||
// Colorized message for console printing.
|
||||
func (m retentionCmdMessage) String() string {
|
||||
var color, msg string
|
||||
ed := ""
|
||||
if m.Op == "clear" {
|
||||
ed = "ed"
|
||||
}
|
||||
|
||||
if m.Err != nil {
|
||||
color = "RetentionFailure"
|
||||
msg = fmt.Sprintf("Unable to %s object retention on `%s`: %s", m.Op, m.URLPath, m.Err)
|
||||
} else {
|
||||
color = "RetentionSuccess"
|
||||
msg = fmt.Sprintf("Object retention successfully %s%s for `%s`", m.Op, ed, m.URLPath)
|
||||
}
|
||||
if m.VersionID != "" {
|
||||
msg += fmt.Sprintf(" (version-id=%s)", m.VersionID)
|
||||
}
|
||||
msg += "."
|
||||
return console.Colorize(color, msg)
|
||||
}
|
||||
|
||||
// JSON'ified message for scripting.
|
||||
func (m retentionCmdMessage) JSON() string {
|
||||
if m.Err != nil {
|
||||
m.Status = "failure"
|
||||
}
|
||||
msgBytes, e := json.MarshalIndent(m, "", " ")
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
return string(msgBytes)
|
||||
}
|
||||
|
||||
// Structured message depending on the type of console.
|
||||
type lockCmdMessage struct {
|
||||
Enabled string `json:"enabled"`
|
||||
Mode minio.RetentionMode `json:"mode"`
|
||||
Validity string `json:"validity"`
|
||||
Status string `json:"status"`
|
||||
}
|
||||
|
||||
// Colorized message for console printing.
|
||||
func (m lockCmdMessage) String() string {
|
||||
if m.Mode == "" {
|
||||
return console.Colorize("Clear", "Object lock configuration cleared successfully")
|
||||
}
|
||||
|
||||
return fmt.Sprintf("%s mode is enabled for %s", console.Colorize("Mode", m.Mode), console.Colorize("Validity", m.Validity))
|
||||
}
|
||||
|
||||
// JSON'ified message for scripting.
|
||||
func (m lockCmdMessage) JSON() string {
|
||||
msgBytes, e := json.MarshalIndent(m, "", " ")
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
return string(msgBytes)
|
||||
}
|
||||
|
||||
func getRetainUntilDate(validity uint64, unit minio.ValidityUnit) (string, *probe.Error) {
|
||||
if validity == 0 {
|
||||
return "", probe.NewError(fmt.Errorf("invalid validity '%v'", validity))
|
||||
}
|
||||
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)
|
||||
|
||||
return timeStr, nil
|
||||
}
|
||||
|
||||
func setRetentionSingle(ctx context.Context, op, alias, url, versionID string, mode minio.RetentionMode, retainUntil time.Time, bypassGovernance bool) *probe.Error {
|
||||
newClnt, err := newClientFromAlias(alias, url)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
msg := retentionCmdMessage{
|
||||
Op: op,
|
||||
Mode: mode,
|
||||
URLPath: urlJoinPath(alias, url),
|
||||
VersionID: versionID,
|
||||
}
|
||||
|
||||
err = newClnt.PutObjectRetention(ctx, versionID, mode, retainUntil, bypassGovernance)
|
||||
if err != nil {
|
||||
msg.Err = err.ToGoError()
|
||||
msg.Status = "failure"
|
||||
} else {
|
||||
msg.Status = "success"
|
||||
}
|
||||
|
||||
printMsg(msg)
|
||||
return err
|
||||
}
|
||||
|
||||
func parseRetentionValidity(validityStr string) (uint64, minio.ValidityUnit, *probe.Error) {
|
||||
unitStr := string(validityStr[len(validityStr)-1])
|
||||
validityStr = validityStr[:len(validityStr)-1]
|
||||
validity, e := strconv.ParseUint(validityStr, 10, 64)
|
||||
if e != nil {
|
||||
return 0, "", probe.NewError(e).Trace(validityStr)
|
||||
}
|
||||
|
||||
var unit minio.ValidityUnit
|
||||
switch unitStr {
|
||||
case "d", "D":
|
||||
unit = minio.Days
|
||||
case "y", "Y":
|
||||
unit = minio.Years
|
||||
default:
|
||||
return 0, "", errInvalidArgument().Trace(unitStr)
|
||||
}
|
||||
|
||||
return validity, unit, nil
|
||||
}
|
||||
|
||||
// Check if the bucket corresponding to the target url has
|
||||
// object locking enabled, this to show a pretty error message
|
||||
func checkObjectLockSupport(ctx context.Context, aliasedURL string) {
|
||||
clnt, err := newClient(aliasedURL)
|
||||
if err != nil {
|
||||
fatalIf(err.Trace(), "Unable to parse the provided url.")
|
||||
}
|
||||
|
||||
status, _, _, _, err := clnt.GetObjectLockConfig(ctx)
|
||||
if err != nil {
|
||||
fatalIf(err.Trace(), "Unable to get bucket object lock configuration from `%s`", aliasedURL)
|
||||
}
|
||||
|
||||
if status != "Enabled" {
|
||||
fatalIf(errDummy().Trace(), "Remote bucket does not support locking `%s`", aliasedURL)
|
||||
}
|
||||
}
|
||||
|
||||
// Apply Retention for one object/version or many objects within a given prefix.
|
||||
func applyRetention(ctx context.Context, op, target, versionID string, timeRef time.Time, withOlderVersions, isRecursive bool,
|
||||
mode minio.RetentionMode, validity uint64, unit minio.ValidityUnit, bypassGovernance bool) error {
|
||||
clnt, err := newClient(target)
|
||||
if err != nil {
|
||||
fatalIf(err.Trace(), "Unable to parse the provided url.")
|
||||
}
|
||||
|
||||
// Quit early if urlStr does not point to an S3 server
|
||||
switch clnt.(type) {
|
||||
case *S3Client:
|
||||
default:
|
||||
fatal(errDummy().Trace(), "Retention is supported only for S3 servers.")
|
||||
}
|
||||
|
||||
var until time.Time
|
||||
if mode != "" {
|
||||
timeStr, err := getRetainUntilDate(validity, unit)
|
||||
if err != nil {
|
||||
return err.ToGoError()
|
||||
|
||||
}
|
||||
var e error
|
||||
until, e = time.Parse(time.RFC3339, timeStr)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
}
|
||||
|
||||
alias, urlStr, _ := mustExpandAlias(target)
|
||||
if versionID != "" || !isRecursive && !withOlderVersions {
|
||||
err := setRetentionSingle(ctx, op, alias, urlStr, versionID, mode, until, bypassGovernance)
|
||||
fatalIf(err.Trace(), "Unable to set retention on `%s`", target)
|
||||
return nil
|
||||
}
|
||||
|
||||
lstOptions := ListOptions{isRecursive: isRecursive, showDir: DirNone}
|
||||
if !timeRef.IsZero() {
|
||||
lstOptions.withOlderVersions = withOlderVersions
|
||||
lstOptions.withDeleteMarkers = true
|
||||
lstOptions.timeRef = timeRef
|
||||
}
|
||||
|
||||
var cErr error
|
||||
var atLeastOneRetentionApplied bool
|
||||
|
||||
for content := range clnt.List(ctx, lstOptions) {
|
||||
if content.Err != nil {
|
||||
errorIf(content.Err.Trace(clnt.GetURL().String()), "Unable to list folder.")
|
||||
cErr = exitStatus(globalErrorExitStatus) // Set the exit status.
|
||||
continue
|
||||
}
|
||||
|
||||
// The spec does not allow setting retention on delete marker
|
||||
if content.IsDeleteMarker {
|
||||
continue
|
||||
}
|
||||
|
||||
if !isRecursive && alias+getKey(content) != getStandardizedURL(target) {
|
||||
break
|
||||
}
|
||||
|
||||
err := setRetentionSingle(ctx, op, alias, content.URL.String(), content.VersionID, mode, until, bypassGovernance)
|
||||
if err != nil {
|
||||
errorIf(err.Trace(clnt.GetURL().String()), "Invalid URL")
|
||||
continue
|
||||
}
|
||||
|
||||
atLeastOneRetentionApplied = true
|
||||
}
|
||||
|
||||
if !atLeastOneRetentionApplied {
|
||||
errorIf(errDummy().Trace(clnt.GetURL().String()), "Unable to find any object/version to "+op+" its retention.")
|
||||
cErr = exitStatus(globalErrorExitStatus) // Set the exit status.
|
||||
}
|
||||
|
||||
return cErr
|
||||
}
|
||||
|
||||
// applyBucketLock - set object lock configuration.
|
||||
func applyBucketLock(op string, urlStr string, mode minio.RetentionMode, validity uint64, unit minio.ValidityUnit) error {
|
||||
client, err := newClient(urlStr)
|
||||
if err != nil {
|
||||
fatalIf(err.Trace(), "Unable to parse the provided url.")
|
||||
}
|
||||
|
||||
ctx, cancelLock := context.WithCancel(globalContext)
|
||||
defer cancelLock()
|
||||
if op == "clear" || mode != "" {
|
||||
err = client.SetObjectLockConfig(ctx, mode, validity, unit)
|
||||
fatalIf(err, "Unable to apply object lock configuration on the specified bucket.")
|
||||
} else {
|
||||
_, mode, validity, unit, err = client.GetObjectLockConfig(ctx)
|
||||
fatalIf(err, "Unable to apply object lock configuration on the specified bucket.")
|
||||
}
|
||||
|
||||
printMsg(lockCmdMessage{
|
||||
Enabled: "Enabled",
|
||||
Mode: mode,
|
||||
Validity: fmt.Sprintf("%d%s", validity, unit),
|
||||
Status: "success",
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// showBucketLock - show object lock configuration.
|
||||
func showBucketLock(urlStr string) error {
|
||||
client, err := newClient(urlStr)
|
||||
if err != nil {
|
||||
fatalIf(err.Trace(), "Unable to parse the provided url.")
|
||||
}
|
||||
|
||||
ctx, cancelLock := context.WithCancel(globalContext)
|
||||
defer cancelLock()
|
||||
|
||||
status, mode, validity, unit, err := client.GetObjectLockConfig(ctx)
|
||||
fatalIf(err, "Unable to get object lock configuration on the specified bucket.")
|
||||
|
||||
printMsg(lockCmdMessage{
|
||||
Enabled: status,
|
||||
Mode: mode,
|
||||
Validity: fmt.Sprintf("%d%s", validity, unit),
|
||||
Status: "success",
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,384 @@
|
||||
/*
|
||||
* MinIO Client (C) 2019-2020 MinIO, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
json "github.com/minio/mc/pkg/colorjson"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/minio-go/v7"
|
||||
"github.com/minio/minio/pkg/console"
|
||||
)
|
||||
|
||||
var (
|
||||
retentionInfoFlags = []cli.Flag{
|
||||
cli.BoolFlag{
|
||||
Name: "recursive, r",
|
||||
Usage: "show retention info recursively",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "version-id, vid",
|
||||
Usage: "show retention info of specific object version",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "rewind",
|
||||
Usage: "roll back object(s) to current version at specified time",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "versions",
|
||||
Usage: "show retention info on object(s) and all its versions",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "default",
|
||||
Usage: "show bucket default retention mode",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
var retentionInfoCmd = cli.Command{
|
||||
Name: "info",
|
||||
Usage: "show retention for object(s)",
|
||||
Action: mainRetentionInfo,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: append(retentionInfoFlags, globalFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} [FLAGS] [governance | compliance] VALIDITY TARGET
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
|
||||
EXAMPLES:
|
||||
1. Show object retention for a specific object
|
||||
$ {{.HelpName}} myminio/mybucket/prefix/obj.csv
|
||||
|
||||
2. Show object retention for recursively for all objects at a given prefix
|
||||
$ {{.HelpName}} myminio/mybucket/prefix --recursive
|
||||
|
||||
3. Show object retention to a specific version of a specific object
|
||||
$ {{.HelpName}} myminio/mybucket/prefix/obj.csv --version-id "3Jr2x6fqlBUsVzbvPihBO3HgNpgZgAnp"
|
||||
|
||||
4. Show object retention for recursively for all versions of all objects under prefix
|
||||
$ {{.HelpName}} myminio/mybucket/prefix --recursive --versions
|
||||
|
||||
5. Show default lock retention configuration for a bucket
|
||||
$ {{.HelpName}} --default myminio/mybucket/
|
||||
`}
|
||||
|
||||
func parseInfoRetentionArgs(cliCtx *cli.Context) (target, versionID string, recursive bool, timeRef time.Time, withVersions, defaultMode bool) {
|
||||
args := cliCtx.Args()
|
||||
|
||||
target = args[0]
|
||||
if target == "" {
|
||||
fatalIf(errInvalidArgument().Trace(), "invalid target url '%v'", target)
|
||||
}
|
||||
|
||||
versionID = cliCtx.String("version-id")
|
||||
timeRef = parseRewindFlag(cliCtx.String("rewind"))
|
||||
withVersions = cliCtx.Bool("versions")
|
||||
recursive = cliCtx.Bool("recursive")
|
||||
defaultMode = cliCtx.Bool("default")
|
||||
return
|
||||
}
|
||||
|
||||
// Structured message depending on the type of console.
|
||||
type retentionInfoMessage struct {
|
||||
Mode minio.RetentionMode `json:"mode"`
|
||||
Until time.Time `json:"until"`
|
||||
URLPath string `json:"urlpath"`
|
||||
VersionID string `json:"versionID"`
|
||||
Status string `json:"status"`
|
||||
Err error `json:"error"`
|
||||
}
|
||||
|
||||
type retentionInfoMessageList retentionInfoMessage
|
||||
|
||||
func (m *retentionInfoMessageList) SetErr(e error) {
|
||||
m.Err = e
|
||||
}
|
||||
|
||||
func (m *retentionInfoMessageList) SetStatus(status string) {
|
||||
m.Status = status
|
||||
}
|
||||
|
||||
func (m *retentionInfoMessageList) SetMode(mode minio.RetentionMode) {
|
||||
m.Mode = mode
|
||||
}
|
||||
|
||||
func (m *retentionInfoMessageList) SetUntil(until time.Time) {
|
||||
m.Until = until
|
||||
}
|
||||
|
||||
// Colorized message for console printing.
|
||||
func (m retentionInfoMessageList) String() string {
|
||||
if m.Err != nil {
|
||||
return console.Colorize("RetentionFailure", fmt.Sprintf("Unable to get get object retention on `%s`: %s", m.URLPath, m.Err))
|
||||
}
|
||||
|
||||
var msg string
|
||||
var retentionField string
|
||||
|
||||
if m.Mode == "" {
|
||||
retentionField += console.Colorize("RetentionNotFound", "NO RETENTION")
|
||||
} else {
|
||||
exp := ""
|
||||
if m.Mode == minio.Governance {
|
||||
now := time.Now()
|
||||
if now.After(m.Until) {
|
||||
exp = "EXPIRED"
|
||||
}
|
||||
}
|
||||
retentionField += console.Colorize("RetentionSuccess", m.Mode.String()) + " " + console.Colorize("RetentionExpired", exp)
|
||||
}
|
||||
|
||||
msg += "[ " + centerText(retentionField, 18) + " ] "
|
||||
|
||||
if m.VersionID != "" {
|
||||
msg += console.Colorize("RetentionVersionID", m.VersionID+" ")
|
||||
}
|
||||
|
||||
msg += m.URLPath
|
||||
return msg
|
||||
}
|
||||
|
||||
// JSON'ified message for scripting.
|
||||
func (m retentionInfoMessageList) JSON() string {
|
||||
if m.Err != nil {
|
||||
m.Status = "failure"
|
||||
}
|
||||
msgBytes, e := json.MarshalIndent(m, "", " ")
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
return string(msgBytes)
|
||||
}
|
||||
|
||||
type retentionInfoMessageRecord retentionInfoMessage
|
||||
|
||||
func (m *retentionInfoMessageRecord) SetErr(e error) {
|
||||
m.Err = e
|
||||
}
|
||||
|
||||
func (m *retentionInfoMessageRecord) SetStatus(status string) {
|
||||
m.Status = status
|
||||
}
|
||||
|
||||
func (m *retentionInfoMessageRecord) SetMode(mode minio.RetentionMode) {
|
||||
m.Mode = mode
|
||||
}
|
||||
|
||||
func (m *retentionInfoMessageRecord) SetUntil(until time.Time) {
|
||||
m.Until = until
|
||||
}
|
||||
|
||||
// Colorized message for console printing.
|
||||
func (m retentionInfoMessageRecord) String() string {
|
||||
if m.Err != nil {
|
||||
return console.Colorize("RetentionFailure", fmt.Sprintf("Unable to get object retention on `%s`: %s", m.URLPath, m.Err))
|
||||
}
|
||||
|
||||
var msg strings.Builder
|
||||
fmt.Fprintf(&msg, "Name : %s\n", console.Colorize("RetentionSuccess", m.URLPath))
|
||||
|
||||
if m.VersionID != "" {
|
||||
fmt.Fprintf(&msg, "Version : %s\n", console.Colorize("RetentionSuccess", m.VersionID))
|
||||
}
|
||||
|
||||
fmt.Fprintf(&msg, "Mode : ")
|
||||
if m.Mode == "" {
|
||||
fmt.Fprintf(&msg, console.Colorize("RetentionNotFound", "NO RETENTION"))
|
||||
} else {
|
||||
fmt.Fprintf(&msg, console.Colorize("RetentionSuccess", m.Mode))
|
||||
if !m.Until.IsZero() {
|
||||
msg.WriteString(", ")
|
||||
exp := ""
|
||||
now := time.Now()
|
||||
if now.After(m.Until) {
|
||||
prettyDuration := timeDurationToHumanizedDuration(now.Sub(m.Until)).StringShort()
|
||||
exp = console.Colorize("RetentionExpired", "expired "+prettyDuration+" ago")
|
||||
} else {
|
||||
prettyDuration := timeDurationToHumanizedDuration(m.Until.Sub(now)).StringShort()
|
||||
exp = console.Colorize("RetentionSuccess", "expiring in "+prettyDuration)
|
||||
}
|
||||
fmt.Fprintf(&msg, exp)
|
||||
}
|
||||
}
|
||||
fmt.Fprintf(&msg, "\n")
|
||||
return msg.String()
|
||||
}
|
||||
|
||||
// JSON'ified message for scripting.
|
||||
func (m retentionInfoMessageRecord) JSON() string {
|
||||
if m.Err != nil {
|
||||
m.Status = "failure"
|
||||
}
|
||||
msgBytes, e := json.MarshalIndent(m, "", " ")
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
return string(msgBytes)
|
||||
}
|
||||
|
||||
type retentionInfoMsg interface {
|
||||
message
|
||||
SetErr(error)
|
||||
SetStatus(string)
|
||||
SetMode(minio.RetentionMode)
|
||||
SetUntil(time.Time)
|
||||
}
|
||||
|
||||
// Show retention info for a single object or version
|
||||
func infoRetentionSingle(ctx context.Context, alias, url, versionID string, listStyle bool) *probe.Error {
|
||||
newClnt, err := newClientFromAlias(alias, url)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var msg retentionInfoMsg
|
||||
|
||||
if listStyle {
|
||||
msg = &retentionInfoMessageList{
|
||||
URLPath: urlJoinPath(alias, url),
|
||||
VersionID: versionID,
|
||||
}
|
||||
} else {
|
||||
msg = &retentionInfoMessageRecord{
|
||||
URLPath: urlJoinPath(alias, url),
|
||||
VersionID: versionID,
|
||||
}
|
||||
}
|
||||
|
||||
mode, until, err := newClnt.GetObjectRetention(ctx, versionID)
|
||||
if err != nil {
|
||||
errResp := minio.ToErrorResponse(err.ToGoError())
|
||||
if errResp.Code != "NoSuchObjectLockConfiguration" {
|
||||
msg.SetErr(err.ToGoError())
|
||||
msg.SetStatus("failure")
|
||||
printMsg(msg)
|
||||
return err
|
||||
}
|
||||
err = nil
|
||||
}
|
||||
|
||||
msg.SetStatus("success")
|
||||
msg.SetMode(mode)
|
||||
msg.SetUntil(until)
|
||||
|
||||
printMsg(msg)
|
||||
return err
|
||||
}
|
||||
|
||||
// Get Retention for one object/version or many objects within a given prefix.
|
||||
func getRetention(ctx context.Context, target, versionID string, timeRef time.Time, withOlderVersions, isRecursive bool) error {
|
||||
clnt, err := newClient(target)
|
||||
if err != nil {
|
||||
fatalIf(err.Trace(), "Unable to parse the provided url.")
|
||||
}
|
||||
|
||||
// Quit early if urlStr does not point to an S3 server
|
||||
switch clnt.(type) {
|
||||
case *S3Client:
|
||||
default:
|
||||
fatal(errDummy().Trace(), "Retention is supported only for S3 servers.")
|
||||
}
|
||||
|
||||
alias, urlStr, _ := mustExpandAlias(target)
|
||||
if versionID != "" || !isRecursive && !withOlderVersions {
|
||||
err := infoRetentionSingle(ctx, alias, urlStr, versionID, false)
|
||||
if err != nil {
|
||||
return exitStatus(globalErrorExitStatus)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
lstOptions := ListOptions{isRecursive: isRecursive, showDir: DirNone}
|
||||
if !timeRef.IsZero() {
|
||||
lstOptions.withOlderVersions = withOlderVersions
|
||||
lstOptions.withDeleteMarkers = true
|
||||
lstOptions.timeRef = timeRef
|
||||
}
|
||||
|
||||
var cErr error
|
||||
var atLeastOneObjectOrVersionFound bool
|
||||
|
||||
for content := range clnt.List(ctx, lstOptions) {
|
||||
if content.Err != nil {
|
||||
errorIf(content.Err.Trace(clnt.GetURL().String()), "Unable to list folder.")
|
||||
cErr = exitStatus(globalErrorExitStatus) // Set the exit status.
|
||||
continue
|
||||
}
|
||||
// The spec does not allow setting retention on delete marker
|
||||
if content.IsDeleteMarker {
|
||||
continue
|
||||
}
|
||||
|
||||
if !isRecursive && alias+getKey(content) != getStandardizedURL(target) {
|
||||
break
|
||||
}
|
||||
|
||||
err := infoRetentionSingle(ctx, alias, content.URL.String(), content.VersionID, true)
|
||||
if err != nil {
|
||||
errorIf(err.Trace(clnt.GetURL().String()), "Invalid URL")
|
||||
cErr = exitStatus(globalErrorExitStatus)
|
||||
continue
|
||||
}
|
||||
|
||||
atLeastOneObjectOrVersionFound = true
|
||||
}
|
||||
|
||||
if !atLeastOneObjectOrVersionFound {
|
||||
errorIf(errDummy().Trace(clnt.GetURL().String()), "Unable to find any object/version to show its retention.")
|
||||
cErr = exitStatus(globalErrorExitStatus) // Set the exit status.
|
||||
}
|
||||
|
||||
return cErr
|
||||
}
|
||||
|
||||
// main for retention info command.
|
||||
func mainRetentionInfo(cliCtx *cli.Context) error {
|
||||
ctx, cancelSetRetention := context.WithCancel(globalContext)
|
||||
defer cancelSetRetention()
|
||||
|
||||
console.SetColor("RetentionSuccess", color.New(color.FgGreen, color.Bold))
|
||||
console.SetColor("RetentionNotFound", color.New(color.FgYellow))
|
||||
console.SetColor("RetentionVersionID", color.New(color.FgGreen))
|
||||
console.SetColor("RetentionExpired", color.New(color.FgRed, color.Bold))
|
||||
console.SetColor("RetentionFailure", color.New(color.FgYellow))
|
||||
|
||||
if len(cliCtx.Args()) != 1 {
|
||||
cli.ShowCommandHelpAndExit(cliCtx, "info", 1)
|
||||
}
|
||||
|
||||
target, versionID, recursive, rewind, withVersions, bucketMode := parseInfoRetentionArgs(cliCtx)
|
||||
|
||||
checkObjectLockSupport(ctx, target)
|
||||
|
||||
if bucketMode {
|
||||
return showBucketLock(target)
|
||||
}
|
||||
|
||||
if withVersions && rewind.IsZero() {
|
||||
rewind = time.Now().UTC()
|
||||
}
|
||||
|
||||
return getRetention(ctx, target, versionID, rewind, withVersions, recursive)
|
||||
}
|
||||
+9
-191
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* MinIO Client (C) 2019 MinIO, Inc.
|
||||
* MinIO Client (C) 2019-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.
|
||||
@@ -17,206 +17,24 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
json "github.com/minio/mc/pkg/colorjson"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
minio "github.com/minio/minio-go/v7"
|
||||
"github.com/minio/minio/pkg/console"
|
||||
)
|
||||
|
||||
var (
|
||||
rFlags = []cli.Flag{
|
||||
cli.BoolFlag{
|
||||
Name: "recursive, r",
|
||||
Usage: "apply retention recursively",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: bypass,
|
||||
Usage: "bypass governance",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
var bypass = "bypass"
|
||||
|
||||
var retentionCmd = cli.Command{
|
||||
Name: "retention",
|
||||
Usage: "set retention for object(s)",
|
||||
Action: mainRetention,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: append(rFlags, 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 a specific object
|
||||
$ {{.HelpName}} myminio/mybucket/prefix/obj.csv compliance 30d
|
||||
|
||||
2. Set object retention for recursively for all objects at a given prefix
|
||||
$ {{.HelpName}} myminio/mybucket/prefix compliance 30d --recursive
|
||||
`,
|
||||
}
|
||||
|
||||
// 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", fmt.Sprintf("Unable to set object retention on `%s`: %s", m.URLPath, m.Err))
|
||||
}
|
||||
return console.Colorize("RetentionSuccess", fmt.Sprintf("Object retention successfully set for `%s`", m.URLPath))
|
||||
}
|
||||
|
||||
// JSON'ified message for scripting.
|
||||
func (m retentionCmdMessage) JSON() string {
|
||||
if m.Err != nil {
|
||||
m.Status = "failure"
|
||||
}
|
||||
msgBytes, e := json.MarshalIndent(m, "", " ")
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
return string(msgBytes)
|
||||
}
|
||||
|
||||
func getRetainUntilDate(validity uint64, unit minio.ValidityUnit) (string, *probe.Error) {
|
||||
if validity == 0 {
|
||||
return "", probe.NewError(fmt.Errorf("invalid validity '%v'", validity))
|
||||
}
|
||||
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)
|
||||
|
||||
return timeStr, nil
|
||||
}
|
||||
|
||||
// setRetention - Set Retention for all objects within a given prefix.
|
||||
func setRetention(urlStr string, mode minio.RetentionMode, validity uint64, unit minio.ValidityUnit, bypassGovernance, isRecursive bool) error {
|
||||
ctx, cancelSetRetention := context.WithCancel(globalContext)
|
||||
defer cancelSetRetention()
|
||||
|
||||
clnt, err := newClient(urlStr)
|
||||
if err != nil {
|
||||
fatalIf(err.Trace(), "Unable to parse the provided url.")
|
||||
}
|
||||
|
||||
// Quit early if urlStr does not point to an S3 server
|
||||
switch clnt.(type) {
|
||||
case *fsClient:
|
||||
fatal(errDummy().Trace(), "Retention for filesystem not supported.")
|
||||
}
|
||||
|
||||
alias, _, _ := mustExpandAlias(urlStr)
|
||||
|
||||
var cErr error
|
||||
for content := range clnt.List(ctx, ListOptions{isRecursive: isRecursive, showDir: DirNone}) {
|
||||
if content.Err != nil {
|
||||
errorIf(content.Err.Trace(clnt.GetURL().String()), "Unable to list folder.")
|
||||
cErr = exitStatus(globalErrorExitStatus) // Set the exit status.
|
||||
continue
|
||||
}
|
||||
timeStr, err := getRetainUntilDate(validity, unit)
|
||||
if err != nil {
|
||||
errorIf(err.Trace(clnt.GetURL().String()), "Invalid retention date")
|
||||
continue
|
||||
}
|
||||
retainUntil, e := time.Parse(time.RFC3339, timeStr)
|
||||
if e != nil {
|
||||
errorIf(probe.NewError(e).Trace(clnt.GetURL().String()), "Invalid retention date")
|
||||
continue
|
||||
}
|
||||
|
||||
newClnt, err := newClientFromAlias(alias, content.URL.String())
|
||||
if err != nil {
|
||||
errorIf(err.Trace(clnt.GetURL().String()), "Invalid URL")
|
||||
continue
|
||||
}
|
||||
err = newClnt.PutObjectRetention(ctx, mode, retainUntil, bypassGovernance)
|
||||
if err != nil {
|
||||
printMsg(retentionCmdMessage{
|
||||
Mode: mode,
|
||||
Validity: fmt.Sprintf("%d%s", validity, unit),
|
||||
Status: "failure",
|
||||
URLPath: urlJoinPath(alias, content.URL.Path),
|
||||
Err: err.ToGoError(),
|
||||
})
|
||||
} else {
|
||||
printMsg(retentionCmdMessage{
|
||||
Mode: mode,
|
||||
Validity: fmt.Sprintf("%d%s", validity, unit),
|
||||
Status: "success",
|
||||
URLPath: urlJoinPath(alias, content.URL.Path),
|
||||
})
|
||||
}
|
||||
}
|
||||
return cErr
|
||||
Flags: globalFlags,
|
||||
Subcommands: []cli.Command{
|
||||
retentionSetCmd,
|
||||
retentionClearCmd,
|
||||
retentionInfoCmd,
|
||||
},
|
||||
}
|
||||
|
||||
// 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))
|
||||
args := ctx.Args()
|
||||
|
||||
var urlStr string
|
||||
var mode minio.RetentionMode
|
||||
var validity uint64
|
||||
var unit minio.ValidityUnit
|
||||
|
||||
switch l := len(args); l {
|
||||
case 3:
|
||||
urlStr = args[0]
|
||||
mode = minio.RetentionMode(strings.ToUpper(args[1]))
|
||||
if !mode.IsValid() {
|
||||
fatalIf(errInvalidArgument().Trace(args...), "invalid retention mode '%v'", mode)
|
||||
}
|
||||
|
||||
validityStr := args[2]
|
||||
unitStr := validityStr[len(validityStr)-1]
|
||||
validityStr = validityStr[:len(validityStr)-1]
|
||||
|
||||
var e error
|
||||
validity, e = strconv.ParseUint(validityStr, 10, 64)
|
||||
if e != nil {
|
||||
fatalIf(probe.NewError(e).Trace(urlStr), "invalid validity '%v'", validityStr)
|
||||
}
|
||||
|
||||
switch unitStr {
|
||||
case 'd', 'D':
|
||||
unit = minio.Days
|
||||
case 'y', 'Y':
|
||||
unit = minio.Years
|
||||
default:
|
||||
fatalIf(errInvalidArgument().Trace(urlStr), "invalid validity format '%v'", unitStr)
|
||||
}
|
||||
default:
|
||||
cli.ShowCommandHelpAndExit(ctx, "retention", 1)
|
||||
}
|
||||
return setRetention(urlStr, mode, validity, unit, ctx.Bool("bypass"), ctx.Bool("recursive"))
|
||||
cli.ShowCommandHelpAndExit(ctx, ctx.Args().First(), 1)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
/*
|
||||
* MinIO Client (C) 2019-2020 MinIO, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
minio "github.com/minio/minio-go/v7"
|
||||
"github.com/minio/minio/pkg/console"
|
||||
)
|
||||
|
||||
var (
|
||||
retentionSetFlags = []cli.Flag{
|
||||
cli.BoolFlag{
|
||||
Name: "recursive, r",
|
||||
Usage: "apply retention recursively",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "bypass",
|
||||
Usage: "bypass governance",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "version-id, vid",
|
||||
Usage: "apply retention to a specific object version",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "rewind",
|
||||
Usage: "roll back object(s) to current version at specified time",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "versions",
|
||||
Usage: "apply retention object(s) and all its versions",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "default",
|
||||
Usage: "set bucket default retention mode",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
var retentionSetCmd = cli.Command{
|
||||
Name: "set",
|
||||
Usage: "set retention for object(s)",
|
||||
Action: mainRetentionSet,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: append(retentionSetFlags, globalFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} [FLAGS] [governance | compliance] VALIDITY TARGET
|
||||
|
||||
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 a specific object
|
||||
$ {{.HelpName}} compliance 30d myminio/mybucket/prefix/obj.csv
|
||||
|
||||
2. Set object retention for recursively for all objects at a given prefix
|
||||
$ {{.HelpName}} governance 30d myminio/mybucket/prefix --recursive
|
||||
|
||||
3. Set object retention to a specific version of a specific object
|
||||
$ {{.HelpName}} governance 30d myminio/mybucket/prefix/obj.csv --version-id "3Jr2x6fqlBUsVzbvPihBO3HgNpgZgAnp"
|
||||
|
||||
4. Set object retention for recursively for all versions of all objects
|
||||
$ {{.HelpName}} governance 30d myminio/mybucket/prefix --recursive --versions
|
||||
|
||||
5. Set default lock retention configuration for a bucket
|
||||
$ {{.HelpName}} --default governance 30d myminio/mybucket/
|
||||
|
||||
`}
|
||||
|
||||
func parseSetRetentionArgs(cliCtx *cli.Context) (target, versionID string, recursive bool, timeRef time.Time, withVersions bool, mode minio.RetentionMode, validity uint64, unit minio.ValidityUnit, bypass, bucketMode bool) {
|
||||
args := cliCtx.Args()
|
||||
mode = minio.RetentionMode(strings.ToUpper(args[0]))
|
||||
if !mode.IsValid() {
|
||||
fatalIf(errInvalidArgument().Trace(args...), "invalid retention mode '%v'", mode)
|
||||
}
|
||||
|
||||
var err *probe.Error
|
||||
validity, unit, err = parseRetentionValidity(args[1])
|
||||
fatalIf(err.Trace(args[1]), "invalid validity argument")
|
||||
|
||||
target = args[2]
|
||||
if target == "" {
|
||||
fatalIf(errInvalidArgument().Trace(), "invalid target url '%v'", target)
|
||||
}
|
||||
|
||||
versionID = cliCtx.String("version-id")
|
||||
timeRef = parseRewindFlag(cliCtx.String("rewind"))
|
||||
withVersions = cliCtx.Bool("versions")
|
||||
recursive = cliCtx.Bool("recursive")
|
||||
bucketMode = cliCtx.Bool("default")
|
||||
return
|
||||
}
|
||||
|
||||
// Set Retention for one object/version or many objects within a given prefix.
|
||||
func setRetention(ctx context.Context, target, versionID string, timeRef time.Time, withOlderVersions, isRecursive bool,
|
||||
mode minio.RetentionMode, validity uint64, unit minio.ValidityUnit, bypassGovernance bool) error {
|
||||
return applyRetention(ctx, "set", target, versionID, timeRef, withOlderVersions, isRecursive, mode, validity, unit, bypassGovernance)
|
||||
}
|
||||
|
||||
func setBucketLock(urlStr string, mode minio.RetentionMode, validity uint64, unit minio.ValidityUnit) error {
|
||||
return applyBucketLock("set", urlStr, mode, validity, unit)
|
||||
}
|
||||
|
||||
// main for retention set command.
|
||||
func mainRetentionSet(cliCtx *cli.Context) error {
|
||||
ctx, cancelSetRetention := context.WithCancel(globalContext)
|
||||
defer cancelSetRetention()
|
||||
|
||||
console.SetColor("RetentionSuccess", color.New(color.FgGreen, color.Bold))
|
||||
console.SetColor("RetentionFailure", color.New(color.FgYellow))
|
||||
|
||||
if len(cliCtx.Args()) != 3 {
|
||||
cli.ShowCommandHelpAndExit(cliCtx, "set", 1)
|
||||
}
|
||||
|
||||
target, versionID, recursive, rewind, withVersions, mode, validity, unit, bypass, bucketMode := parseSetRetentionArgs(cliCtx)
|
||||
|
||||
checkObjectLockSupport(ctx, target)
|
||||
|
||||
if bucketMode {
|
||||
return setBucketLock(target, mode, validity, unit)
|
||||
}
|
||||
|
||||
if withVersions && rewind.IsZero() {
|
||||
rewind = time.Now().UTC()
|
||||
}
|
||||
|
||||
return setRetention(ctx, target, versionID, rewind, withVersions, recursive, mode, validity, unit, bypass)
|
||||
}
|
||||
+2
-2
@@ -80,7 +80,7 @@ var (
|
||||
Usage: "remove objects newer than L days, M hours and N minutes",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: bypass,
|
||||
Name: "bypass",
|
||||
Usage: "bypass governance",
|
||||
},
|
||||
}
|
||||
@@ -436,7 +436,7 @@ func mainRm(cliCtx *cli.Context) error {
|
||||
isRecursive := cliCtx.Bool("recursive")
|
||||
isFake := cliCtx.Bool("fake")
|
||||
isStdin := cliCtx.Bool("stdin")
|
||||
isBypass := cliCtx.Bool(bypass)
|
||||
isBypass := cliCtx.Bool("bypass")
|
||||
olderThan := cliCtx.String("older-than")
|
||||
newerThan := cliCtx.String("newer-than")
|
||||
isForce := cliCtx.Bool("force")
|
||||
|
||||
Reference in New Issue
Block a user