legalhold: Refactor & add versioning support (#3343)

This commit is contained in:
Anis Elleuch
2020-09-05 17:11:38 -07:00
committed by GitHub
parent 19c49468b7
commit 7f550f9482
12 changed files with 656 additions and 120 deletions
+1 -1
View File
@@ -97,7 +97,7 @@ func lock(urlStr string, mode minio.RetentionMode, validity uint64, unit minio.V
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)
_, mode, validity, unit, err = client.GetObjectLockConfig(ctx)
fatalIf(err, "Unable to get object lock configuration on the specified bucket.")
}
+11 -3
View File
@@ -926,8 +926,8 @@ func (f *fsClient) SetObjectLockConfig(ctx context.Context, mode minio.Retention
}
// Get object lock configuration of bucket.
func (f *fsClient) GetObjectLockConfig(ctx context.Context) (mode minio.RetentionMode, validity uint64, unit minio.ValidityUnit, err *probe.Error) {
return "", 0, "", probe.NewError(APINotImplemented{
func (f *fsClient) GetObjectLockConfig(ctx context.Context) (status string, mode minio.RetentionMode, validity uint64, unit minio.ValidityUnit, err *probe.Error) {
return "", "", 0, "", probe.NewError(APINotImplemented{
API: "GetObjectLockConfig",
APIType: "filesystem",
})
@@ -950,13 +950,21 @@ func (f *fsClient) PutObjectRetention(ctx context.Context, mode minio.RetentionM
}
// Set object legal hold for a given object.
func (f *fsClient) PutObjectLegalHold(ctx context.Context, lhold minio.LegalHoldStatus) *probe.Error {
func (f *fsClient) PutObjectLegalHold(ctx context.Context, versionID string, lhold minio.LegalHoldStatus) *probe.Error {
return probe.NewError(APINotImplemented{
API: "PutObjectLegalHold",
APIType: "filesystem",
})
}
// Get object legal hold for a given object.
func (f *fsClient) GetObjectLegalHold(ctx context.Context, versionID string) (minio.LegalHoldStatus, *probe.Error) {
return "", probe.NewError(APINotImplemented{
API: "GetObjectLegalHold",
APIType: "filesystem",
})
}
// GetAccess - get access policy permissions.
func (f *fsClient) GetAccess(ctx context.Context) (access string, policyJSON string, err *probe.Error) {
// For windows this feature is not implemented.
+30 -7
View File
@@ -2304,11 +2304,12 @@ func (c *S3Client) PutObjectRetention(ctx context.Context, mode minio.RetentionM
}
// PutObjectLegalHold - Set object legal hold for a given object.
func (c *S3Client) PutObjectLegalHold(ctx context.Context, lhold minio.LegalHoldStatus) *probe.Error {
func (c *S3Client) PutObjectLegalHold(ctx context.Context, versionID string, lhold minio.LegalHoldStatus) *probe.Error {
bucket, object := c.url2BucketAndObject()
if lhold.IsValid() {
opts := minio.PutObjectLegalHoldOptions{
Status: &lhold,
Status: &lhold,
VersionID: versionID,
}
e := c.api.PutObjectLegalHold(ctx, bucket, object, opts)
if e != nil {
@@ -2319,22 +2320,44 @@ func (c *S3Client) PutObjectLegalHold(ctx context.Context, lhold minio.LegalHold
return errInvalidArgument().Trace(c.GetURL().String())
}
// GetObjectLegalHold - Get object legal hold for a given object.
func (c *S3Client) GetObjectLegalHold(ctx context.Context, versionID string) (minio.LegalHoldStatus, *probe.Error) {
var lhold minio.LegalHoldStatus
bucket, object := c.url2BucketAndObject()
opts := minio.GetObjectLegalHoldOptions{
VersionID: versionID,
}
lhPtr, e := c.api.GetObjectLegalHold(ctx, bucket, object, opts)
if e != nil {
errResp := minio.ToErrorResponse(e)
if errResp.Code != "NoSuchObjectLockConfiguration" {
return "", probe.NewError(e).Trace(c.GetURL().String())
}
return "", nil
}
// lhPtr can be nil if there is no legalhold status set
if lhPtr != nil {
lhold = *lhPtr
}
return lhold, nil
}
// GetObjectLockConfig - Get object lock configuration of bucket.
func (c *S3Client) GetObjectLockConfig(ctx context.Context) (minio.RetentionMode, uint64, minio.ValidityUnit, *probe.Error) {
func (c *S3Client) GetObjectLockConfig(ctx context.Context) (string, minio.RetentionMode, uint64, minio.ValidityUnit, *probe.Error) {
bucket, _ := c.url2BucketAndObject()
mode, validity, unit, e := c.api.GetBucketObjectLockConfig(ctx, bucket)
enabled, mode, validity, unit, e := c.api.GetObjectLockConfig(ctx, bucket)
if e != nil {
return "", 0, "", probe.NewError(e).Trace(c.GetURL().String())
return "", "", 0, "", probe.NewError(e).Trace(c.GetURL().String())
}
if mode != nil && validity != nil && unit != nil {
// FIXME: this is too ugly, fix minio-go
vuint64 := uint64(*validity)
return *mode, vuint64, *unit, nil
return enabled, *mode, vuint64, *unit, nil
}
return "", 0, "", probe.NewError(fmt.Errorf("No object lock configuration set on %s", bucket)).Trace(c.GetURL().String())
return enabled, "", 0, "", nil
}
// GetTags - Get tags of bucket or object.
+3 -2
View File
@@ -91,7 +91,7 @@ type Client interface {
MakeBucket(ctx context.Context, region string, ignoreExisting, withLock bool) *probe.Error
// Object lock config
SetObjectLockConfig(ctx context.Context, mode minio.RetentionMode, validity uint64, unit minio.ValidityUnit) *probe.Error
GetObjectLockConfig(ctx context.Context) (mode minio.RetentionMode, validity uint64, unit minio.ValidityUnit, perr *probe.Error)
GetObjectLockConfig(ctx context.Context) (status string, mode minio.RetentionMode, validity uint64, unit minio.ValidityUnit, perr *probe.Error)
// Access policy operations.
GetAccess(ctx context.Context) (access string, policyJSON string, error *probe.Error)
@@ -111,7 +111,8 @@ type Client interface {
// Object Locking related API
PutObjectRetention(ctx context.Context, mode minio.RetentionMode, retainUntilDate time.Time, bypassGovernance bool) *probe.Error
PutObjectLegalHold(ctx context.Context, hold minio.LegalHoldStatus) *probe.Error
PutObjectLegalHold(ctx context.Context, versionID string, hold minio.LegalHoldStatus) *probe.Error
GetObjectLegalHold(ctx context.Context, versionID string) (minio.LegalHoldStatus, *probe.Error)
// I/O operations with expiration
ShareDownload(ctx context.Context, versionID string, expires time.Duration) (string, *probe.Error)
+1 -1
View File
@@ -378,7 +378,7 @@ func doCopySession(ctx context.Context, cancelCopy context.CancelFunc, cli *cli.
// Check if the target bucket has object locking enabled
var withLock bool
if _, _, _, err = tgtClnt.GetObjectLockConfig(ctx); err == nil {
if _, _, _, _, err = tgtClnt.GetObjectLockConfig(ctx); err == nil {
withLock = true
}
+98
View File
@@ -0,0 +1,98 @@
/*
* MinIO Client (C) 2020 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cmd
import (
"context"
"time"
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/minio-go/v7"
"github.com/minio/minio/pkg/console"
)
var (
lhClearFlags = []cli.Flag{
cli.BoolFlag{
Name: "recursive, r",
Usage: "clear legal hold recursively",
},
cli.StringFlag{
Name: "version-id, vid",
Usage: "clear legal hold of a specific object version",
},
cli.StringFlag{
Name: "rewind",
Usage: "clear legal hold on an object version at specified time",
},
cli.BoolFlag{
Name: "versions",
Usage: "clear legal hold on multiple versions of object(s)",
},
}
)
var legalHoldClearCmd = cli.Command{
Name: "clear",
Usage: "clear legal hold for object(s)",
Action: mainLegalHoldClear,
Before: setGlobalsFromContext,
Flags: append(lhClearFlags, globalFlags...),
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} [FLAGS] TARGET
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Disable legal hold on a specific object
$ {{.HelpName}} myminio/mybucket/prefix/obj.csv
2. Disable legal hold on a specific object version
$ {{.HelpName}} myminio/mybucket/prefix/obj.csv --version-id "HiMFUTOowG6ylfNi4LKxD3ieHbgfgrvC"
3. Disable object legal hold recursively for all objects at a prefix
$ {{.HelpName}} myminio/mybucket/prefix --recursive
4. Disable object legal hold recursively for all objects versions older than one year
$ {{.HelpName}} myminio/mybucket/prefix --recursive --rewind 365d --versions
`,
}
// main for legalhold clear command.
func mainLegalHoldClear(cliCtx *cli.Context) error {
console.SetColor("LegalHoldSuccess", color.New(color.FgGreen, color.Bold))
console.SetColor("LegalHoldPartialFailure", color.New(color.FgRed, color.Bold))
console.SetColor("LegalHoldMessageFailure", color.New(color.FgYellow))
targetURL, versionID, timeRef, recursive, withVersions := parseLegalHoldArgs(cliCtx)
if timeRef.IsZero() && withVersions {
timeRef = time.Now().UTC()
}
ctx, cancelCopy := context.WithCancel(globalContext)
defer cancelCopy()
checkBucketLockSupport(ctx, targetURL)
return setLegalHold(ctx, targetURL, versionID, timeRef, withVersions, recursive, minio.LegalHoldDisabled)
}
+242
View File
@@ -0,0 +1,242 @@
/*
* MinIO Client (C) 2020 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cmd
import (
"context"
"fmt"
"path/filepath"
"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 (
lhInfoFlags = []cli.Flag{
cli.BoolFlag{
Name: "recursive, r",
Usage: "show legal hold status recursively",
},
cli.StringFlag{
Name: "version-id, vid",
Usage: "show legal hold status of a specific object version",
},
cli.StringFlag{
Name: "rewind",
Usage: "show legal hold status of an object version at specified time",
},
cli.BoolFlag{
Name: "versions",
Usage: "show legal hold status of multiple versions of object(s)",
},
}
)
var legalHoldInfoCmd = cli.Command{
Name: "info",
Usage: "show legal hold info for object(s)",
Action: mainLegalHoldInfo,
Before: setGlobalsFromContext,
Flags: append(lhInfoFlags, globalFlags...),
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} [FLAGS] TARGET
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Show legal hold on a specific object
$ {{.HelpName}} myminio/mybucket/prefix/obj.csv
2. Show legal hold on a specific object version
$ {{.HelpName}} myminio/mybucket/prefix/obj.csv --version-id "HiMFUTOowG6ylfNi4LKxD3ieHbgfgrvC"
3. Show object legal hold recursively for all objects at a prefix
$ {{.HelpName}} myminio/mybucket/prefix --recursive
4. Show object legal hold recursively for all objects versions older than one year
$ {{.HelpName}} myminio/mybucket/prefix --recursive --rewind 365d --versions
`,
}
// Structured message depending on the type of console.
type legalHoldInfoMessage struct {
LegalHold minio.LegalHoldStatus `json:"legalhold"`
URLPath string `json:"urlpath"`
Key string `json:"key"`
VersionID string `json:"versionID"`
Status string `json:"status"`
Err error `json:"error,omitempty"`
}
// Colorized message for console printing.
func (l legalHoldInfoMessage) String() string {
if l.Err != nil {
return console.Colorize("LegalHoldMessageFailure", "Unable to get object legal hold status `"+l.Key+"`. "+l.Err.Error())
}
var msg string
var legalhold string
switch l.LegalHold {
case "":
legalhold = console.Colorize("LegalHoldNotSet", "Not set")
case minio.LegalHoldEnabled:
legalhold = console.Colorize("LegalHoldOn", l.LegalHold)
case minio.LegalHoldDisabled:
legalhold = console.Colorize("LegalHoldOff", l.LegalHold)
}
msg += "[ " + centerText(legalhold, 8) + " ] "
if l.VersionID != "" {
msg += " " + console.Colorize("LegalHoldVersion", l.VersionID) + " "
}
msg += " "
msg += l.Key
return msg
}
// JSON'ified message for scripting.
func (l legalHoldInfoMessage) JSON() string {
msgBytes, e := json.MarshalIndent(l, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(msgBytes)
}
// showLegalHoldInfo - show legalhold for one or many objects within a given prefix, with or without versioning
func showLegalHoldInfo(ctx context.Context, urlStr, versionID string, timeRef time.Time, withOlderVersions, recursive bool) error {
clnt, err := newClient(urlStr)
if err != nil {
fatalIf(err.Trace(), "Unable to parse the provided url.")
}
prefixPath := clnt.GetURL().Path
prefixPath = filepath.ToSlash(prefixPath)
if !strings.HasSuffix(prefixPath, "/") {
prefixPath = prefixPath[:strings.LastIndex(prefixPath, "/")+1]
}
prefixPath = strings.TrimPrefix(prefixPath, "./")
if !recursive && !withOlderVersions {
lhold, err := clnt.GetObjectLegalHold(ctx, versionID)
if err != nil {
fatalIf(err.Trace(urlStr), "Failed to show legal hold information of `"+urlStr+"`.")
} else {
contentURL := filepath.ToSlash(clnt.GetURL().Path)
key := strings.TrimPrefix(contentURL, prefixPath)
printMsg(legalHoldInfoMessage{
LegalHold: lhold,
Status: "success",
URLPath: clnt.GetURL().String(),
Key: key,
VersionID: versionID,
})
}
return nil
}
alias, _, _ := mustExpandAlias(urlStr)
var cErr error
errorsFound := false
objectsFound := false
lstOptions := ListOptions{isRecursive: recursive, showDir: DirNone}
if !timeRef.IsZero() {
lstOptions.withOlderVersions = withOlderVersions
lstOptions.timeRef = timeRef
}
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
}
if !recursive && alias+getKey(content) != getStandardizedURL(urlStr) {
break
}
objectsFound = true
newClnt, perr := newClientFromAlias(alias, content.URL.String())
if perr != nil {
errorIf(content.Err.Trace(clnt.GetURL().String()), "Invalid URL")
continue
}
lhold, probeErr := newClnt.GetObjectLegalHold(ctx, content.VersionID)
if probeErr != nil {
errorsFound = true
errorIf(probeErr.Trace(content.URL.Path), "Failed to get legal hold information on `"+content.URL.Path+"`")
} else {
if !globalJSON {
contentURL := filepath.ToSlash(content.URL.Path)
key := strings.TrimPrefix(contentURL, prefixPath)
printMsg(legalHoldInfoMessage{
LegalHold: lhold,
Status: "success",
URLPath: content.URL.String(),
Key: key,
VersionID: content.VersionID,
})
}
}
}
if cErr == nil && !globalJSON {
switch {
case errorsFound:
console.Print(console.Colorize("LegalHoldPartialFailure", fmt.Sprintf("Errors found while getting legal hold status on objects with prefix `%s`. \n", urlStr)))
case !objectsFound:
console.Print(console.Colorize("LegalHoldMessageFailure", fmt.Sprintf("No objects/versions found while getting legal hold status with prefix `%s`. \n", urlStr)))
}
}
return cErr
}
// main for legalhold info command.
func mainLegalHoldInfo(cliCtx *cli.Context) error {
console.SetColor("LegalHoldSuccess", color.New(color.FgGreen, color.Bold))
console.SetColor("LegalHoldNotSet", color.New(color.FgYellow))
console.SetColor("LegalHoldOn", color.New(color.FgGreen, color.Bold))
console.SetColor("LegalHoldOff", color.New(color.FgRed, color.Bold))
console.SetColor("LegalHoldVersion", color.New(color.FgGreen))
console.SetColor("LegalHoldPartialFailure", color.New(color.FgRed, color.Bold))
console.SetColor("LegalHoldMessageFailure", color.New(color.FgYellow))
targetURL, versionID, timeRef, recursive, withVersions := parseLegalHoldArgs(cliCtx)
if timeRef.IsZero() && withVersions {
timeRef = time.Now().UTC()
}
ctx, cancelLegalHold := context.WithCancel(globalContext)
defer cancelLegalHold()
checkBucketLockSupport(ctx, targetURL)
return showLegalHoldInfo(ctx, targetURL, versionID, timeRef, withVersions, recursive)
}
+33 -103
View File
@@ -20,52 +20,32 @@ import (
"context"
"encoding/json"
"fmt"
"strings"
"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 (
lhFlags = []cli.Flag{
cli.BoolFlag{
Name: "recursive, r",
Usage: "apply legal hold recursively",
},
}
)
var legalHoldCmd = cli.Command{
Name: "legalhold",
Usage: "set legal hold for object(s)",
Usage: "manage legal hold for object(s)",
Action: mainLegalHold,
Before: setGlobalsFromContext,
Flags: append(lhFlags, globalFlags...),
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} [FLAGS] TARGET [ON | OFF]
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Enable legal hold on a specific object
$ {{.HelpName}} myminio/mybucket/prefix/obj.csv ON
2. Enable object legal hold recursively for all objects at a prefix
$ {{.HelpName}} myminio/mybucket/prefix ON --recursive
`,
Flags: globalFlags,
Subcommands: []cli.Command{
legalHoldSetCmd,
legalHoldClearCmd,
legalHoldInfoCmd,
},
}
// Structured message depending on the type of console.
type legalHoldCmdMessage struct {
LegalHold minio.LegalHoldStatus `json:"legalhold"`
URLPath string `json:"urlpath"`
Key string `json:"key"`
VersionID string `json:"versionID"`
Status string `json:"status"`
Err error `json:"error,omitempty"`
}
@@ -73,9 +53,19 @@ type legalHoldCmdMessage struct {
// Colorized message for console printing.
func (l legalHoldCmdMessage) String() string {
if l.Err != nil {
return console.Colorize("LegalHoldMessageFailure", "Unable to set object legal hold status `"+l.URLPath+"`. "+l.Err.Error())
return console.Colorize("LegalHoldMessageFailure", "Unable to set object legal hold status `"+l.Key+"`. "+l.Err.Error())
}
return console.Colorize("LegalHoldSuccess", fmt.Sprintf("Object legal hold successfully set for `%s`.", l.URLPath))
op := "set"
if l.LegalHold == minio.LegalHoldDisabled {
op = "cleared"
}
msg := fmt.Sprintf("Object legal hold successfully %s for `%s`", op, l.Key)
if l.VersionID != "" {
msg += fmt.Sprintf(" (version-id=%s)", l.VersionID)
}
msg += "."
return console.Colorize("LegalHoldSuccess", msg)
}
// JSON'ified message for scripting.
@@ -85,86 +75,26 @@ func (l legalHoldCmdMessage) JSON() string {
return string(msgBytes)
}
// setRetention - Set Retention for all objects within a given prefix.
func setLegalHold(urlStr string, lhold minio.LegalHoldStatus, isRecursive bool) error {
ctx, cancelLegalHold := context.WithCancel(globalContext)
defer cancelLegalHold()
clnt, err := newClient(urlStr)
// Check if the bucket corresponding to the target url has
// object locking enabled, this to show a pretty error message
func checkBucketLockSupport(ctx context.Context, aliasedURL string) {
clnt, err := newClient(aliasedURL)
if err != nil {
fatalIf(err.Trace(), "Unable to parse the provided url.")
}
if !isRecursive {
err = clnt.PutObjectLegalHold(ctx, lhold)
if err != nil {
errorIf(err.Trace(urlStr), "Failed to set legal hold on `"+urlStr+"` successfully")
} else {
printMsg(legalHoldCmdMessage{
LegalHold: lhold,
Status: "success",
URLPath: urlStr,
})
}
return nil
status, _, _, _, err := clnt.GetObjectLockConfig(ctx)
if err != nil {
fatalIf(err.Trace(), "Unable to get bucket object lock configuration from `%s`", aliasedURL)
}
alias, _, _ := mustExpandAlias(urlStr)
var cErr error
errorsFound := false
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
}
newClnt, perr := newClientFromAlias(alias, content.URL.String())
if perr != nil {
errorIf(content.Err.Trace(clnt.GetURL().String()), "Invalid URL")
continue
}
probeErr := newClnt.PutObjectLegalHold(ctx, lhold)
if probeErr != nil {
errorsFound = true
errorIf(probeErr.Trace(content.URL.Path), "Failed to set legal hold on `"+content.URL.Path+"` successfully")
} else {
if globalJSON {
printMsg(legalHoldCmdMessage{
LegalHold: lhold,
Status: "success",
URLPath: content.URL.Path,
})
}
}
if status != "Enabled" {
fatalIf(errDummy().Trace(), "Remote bucket does not support locking `%s`", aliasedURL)
}
if cErr == nil && !globalJSON {
if errorsFound {
console.Print(console.Colorize("LegalHoldPartialFailure", fmt.Sprintf("Errors found while setting legal hold status on objects with prefix `%s`. \n", urlStr)))
} else {
console.Print(console.Colorize("LegalHoldSuccess", fmt.Sprintf("Object legal hold successfully set for prefix `%s`.\n", urlStr)))
}
}
return cErr
}
// main for retention command.
func mainLegalHold(ctx *cli.Context) error {
console.SetColor("LegalHoldSuccess", color.New(color.FgGreen, color.Bold))
console.SetColor("LegalHoldPartialFailure", color.New(color.FgRed, color.Bold))
console.SetColor("LegalHoldMessageFailure", color.New(color.FgYellow))
args := ctx.Args()
var urlStr string
var lhold minio.LegalHoldStatus
switch l := len(args); l {
case 2:
urlStr = args[0]
lhold = minio.LegalHoldStatus(strings.ToUpper(args[1]))
if !lhold.IsValid() {
fatalIf(errInvalidArgument().Trace(urlStr), "invalid legal hold status '%v'", lhold)
}
default:
cli.ShowCommandHelpAndExit(ctx, "legalhold", 1)
}
return setLegalHold(urlStr, lhold, ctx.Bool("recursive"))
cli.ShowCommandHelp(ctx, ctx.Args().First())
return nil
}
+215
View File
@@ -0,0 +1,215 @@
/*
* MinIO Client (C) 2020 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cmd
import (
"context"
"fmt"
"path/filepath"
"strings"
"time"
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/minio-go/v7"
"github.com/minio/minio/pkg/console"
)
var (
lhSetFlags = []cli.Flag{
cli.BoolFlag{
Name: "recursive, r",
Usage: "apply legal hold recursively",
},
cli.StringFlag{
Name: "version-id, vid",
Usage: "apply legal hold to a specific object version",
},
cli.StringFlag{
Name: "rewind",
Usage: "apply legal hold on an object version at specified time",
},
cli.BoolFlag{
Name: "versions",
Usage: "apply legal hold on multiple versions of an object",
},
}
)
var legalHoldSetCmd = cli.Command{
Name: "set",
Usage: "set legal hold for object(s)",
Action: mainLegalHoldSet,
Before: setGlobalsFromContext,
Flags: append(lhSetFlags, globalFlags...),
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} [FLAGS] TARGET
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Enable legal hold on a specific object
$ {{.HelpName}} myminio/mybucket/prefix/obj.csv
2. Enable legal hold on a specific object version
$ {{.HelpName}} myminio/mybucket/prefix/obj.csv --version-id "HiMFUTOowG6ylfNi4LKxD3ieHbgfgrvC"
3. Enable object legal hold recursively for all objects at a prefix
$ {{.HelpName}} myminio/mybucket/prefix --recursive
4. Enable object legal hold recursively for all objects versions older than one year
$ {{.HelpName}} myminio/mybucket/prefix --recursive --rewind 365d --versions
`,
}
// setLegalHold - Set legalhold for all objects within a given prefix.
func setLegalHold(ctx context.Context, urlStr, versionID string, timeRef time.Time, withOlderVersions, recursive bool, lhold minio.LegalHoldStatus) error {
clnt, err := newClient(urlStr)
if err != nil {
fatalIf(err.Trace(), "Unable to parse the provided url.")
}
prefixPath := clnt.GetURL().Path
prefixPath = filepath.ToSlash(prefixPath)
if !strings.HasSuffix(prefixPath, "/") {
prefixPath = prefixPath[:strings.LastIndex(prefixPath, "/")+1]
}
prefixPath = strings.TrimPrefix(prefixPath, "./")
if !recursive && !withOlderVersions {
err = clnt.PutObjectLegalHold(ctx, versionID, lhold)
if err != nil {
errorIf(err.Trace(urlStr), "Failed to set legal hold on `"+urlStr+"` successfully")
} else {
contentURL := filepath.ToSlash(clnt.GetURL().Path)
key := strings.TrimPrefix(contentURL, prefixPath)
printMsg(legalHoldCmdMessage{
LegalHold: lhold,
Status: "success",
URLPath: clnt.GetURL().String(),
Key: key,
VersionID: versionID,
})
}
return nil
}
alias, _, _ := mustExpandAlias(urlStr)
var cErr error
objectsFound := false
lstOptions := ListOptions{isRecursive: recursive, showDir: DirNone}
if !timeRef.IsZero() {
lstOptions.withOlderVersions = withOlderVersions
lstOptions.timeRef = timeRef
}
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
}
if !recursive && alias+getKey(content) != getStandardizedURL(urlStr) {
break
}
objectsFound = true
newClnt, perr := newClientFromAlias(alias, content.URL.String())
if perr != nil {
errorIf(content.Err.Trace(clnt.GetURL().String()), "Invalid URL")
continue
}
probeErr := newClnt.PutObjectLegalHold(ctx, content.VersionID, lhold)
if probeErr != nil {
errorIf(probeErr.Trace(content.URL.Path), "Failed to set legal hold on `"+content.URL.Path+"` successfully")
} else {
if !globalJSON {
contentURL := filepath.ToSlash(content.URL.Path)
key := strings.TrimPrefix(contentURL, prefixPath)
printMsg(legalHoldCmdMessage{
LegalHold: lhold,
Status: "success",
URLPath: content.URL.String(),
Key: key,
VersionID: content.VersionID,
})
}
}
}
if cErr == nil && !globalJSON {
if !objectsFound {
console.Print(console.Colorize("LegalHoldMessageFailure",
fmt.Sprintf("No objects/versions found while setting legal hold on `%s`. \n", urlStr)))
}
}
return cErr
}
// Validate command line arguments.
func parseLegalHoldArgs(cliCtx *cli.Context) (targetURL, versionID string, timeRef time.Time, recursive, withVersions bool) {
args := cliCtx.Args()
if len(args) != 1 {
cli.ShowCommandHelpAndExit(cliCtx, cliCtx.Command.Name, 1)
}
targetURL = args[0]
if targetURL == "" {
fatalIf(errInvalidArgument(), "You cannot pass an empty target url.")
}
versionID = cliCtx.String("version-id")
recursive = cliCtx.Bool("recursive")
withVersions = cliCtx.Bool("versions")
rewind := cliCtx.String("rewind")
if versionID != "" && (recursive || withVersions || rewind != "") {
fatalIf(errInvalidArgument(), "You cannot pass --version-id with any of --versions, --recursive and --rewind flags.")
}
timeRef = parseRewindFlag(rewind)
return
}
// main for legalhold set command.
func mainLegalHoldSet(cliCtx *cli.Context) error {
console.SetColor("LegalHoldSuccess", color.New(color.FgGreen, color.Bold))
console.SetColor("LegalHoldFailure", color.New(color.FgRed, color.Bold))
console.SetColor("LegalHoldPartialFailure", color.New(color.FgRed, color.Bold))
console.SetColor("LegalHoldMessageFailure", color.New(color.FgYellow))
targetURL, versionID, timeRef, recursive, withVersions := parseLegalHoldArgs(cliCtx)
if timeRef.IsZero() && withVersions {
timeRef = time.Now().UTC()
}
ctx, cancelLegalHold := context.WithCancel(globalContext)
defer cancelLegalHold()
checkBucketLockSupport(ctx, targetURL)
return setLegalHold(ctx, targetURL, versionID, timeRef, withVersions, recursive, minio.LegalHoldEnabled)
}
+2 -2
View File
@@ -787,7 +787,7 @@ func runMirror(ctx context.Context, cancelMirror context.CancelFunc, srcURL, dst
if d.Diff == differInFirst {
withLock := false
mode, validity, unit, err := newSrcClt.GetObjectLockConfig(ctx)
_, mode, validity, unit, err := newSrcClt.GetObjectLockConfig(ctx)
if err == nil {
withLock = true
}
@@ -826,7 +826,7 @@ func runMirror(ctx context.Context, cancelMirror context.CancelFunc, srcURL, dst
}
} else if _, err := dstClt.Stat(ctx, StatOptions{}); err != nil {
withLock := false
mode, validity, unit, err := srcClt.GetObjectLockConfig(ctx)
_, mode, validity, unit, err := srcClt.GetObjectLockConfig(ctx)
if err == nil {
withLock = true
}
+1 -1
View File
@@ -305,7 +305,7 @@ func mainMove(cliCtx *cli.Context) error {
}
if s3Client, ok := client.(*S3Client); ok {
if _, _, _, err = s3Client.GetObjectLockConfig(ctx); err == nil {
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))
}
}
+19
View File
@@ -17,12 +17,16 @@
package cmd
import (
"bytes"
"crypto/tls"
"errors"
"fmt"
"math"
"math/rand"
"net"
"os"
"path/filepath"
"regexp"
"runtime"
"sort"
"strings"
@@ -363,3 +367,18 @@ func matchS3InHost(urlHost string) bool {
}
return false
}
const ansi = "[\u001B\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[a-zA-Z\\d]*)*)?\u0007)|(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PRZcf-ntqry=><~]))"
var reAnsi = regexp.MustCompile(ansi)
func centerText(s string, w int) string {
var sb strings.Builder
textWithoutColor := reAnsi.ReplaceAllString(s, "")
length := len(textWithoutColor)
padding := float64(w-length) / 2
fmt.Fprintf(&sb, "%s", bytes.Repeat([]byte{' '}, int(math.Ceil(padding))))
fmt.Fprintf(&sb, "%s", s)
fmt.Fprintf(&sb, "%s", bytes.Repeat([]byte{' '}, int(math.Floor(padding))))
return sb.String()
}