Compare commits

..
Author SHA1 Message Date
Anis Elleuch 7e9625733d ilm: Add doc to the complete mc guide (#3270) 2020-07-19 12:45:36 -07:00
kannappanr 1513d76ca9 Fix typos in the examples (#3289) 2020-07-10 22:17:54 -07:00
P R 87dc0bf80e mc ilm list cell alignment for text (#3291) 2020-07-10 22:17:54 -07:00
Harshavardhana 69c0d33543 support proper proxy for all transports (#3290)
fixes #3225
2020-07-10 22:17:54 -07:00
Harshavardhana 8d891755e0 move to latest released minio to fix policy (#3288)
fixes #3265
2020-07-10 22:17:54 -07:00
ebozduman a9cd7869eb Fixes copy with partial metadata failure (#3282) 2020-07-10 22:17:54 -07:00
Harshavardhana c40ab338a3 support goreleaser for mc (#3286) 2020-07-10 22:17:54 -07:00
ebozduman 0fcd10d793 Adds support to preserve X-Amz-Meta-Mc-Attrs when os -> fs (#3285) 2020-07-10 22:17:54 -07:00
Anis Elleuch b7b75c5f46 cli: Load global flags in initBeforeRunningCmd (#3283)
app.Before receives a cli.Context but without flags parsed. There is no
point calling ctx.Bool() or ctx.IsSet() at that stage.

However, flags are parsed in commands, so minio initialization and
setting global variables (globalJSON, globalQuiet, etc..) can be moved
to the Before function of all commands.

Avoid setting command.Before for non leaf commands, otherwise Before
function will be called multiples times until it reaches the leaf
command.
2020-07-10 22:17:54 -07:00
Anis Elleuch b97b7b8987 policy: Recalculate permission mode after setting a new one (#3280)
`mc policy set` can confuse users by showing that a bucket has 'none'
policy mode although issuing `mc policy get` will show it is `custom`
when the bucket already other policy statements for some sub-resources.

For better UX, mc will issue another request to get the real policy
mode.
2020-07-10 22:17:54 -07:00
poornas 8f3d514e3b Fix mc cp regression for recursive copy (#3278)
Fixes #3267. Revert commit dc430afe07
which attempted to preserve similar behavior across mc cp and mc
mirror, but introduces a regression for cp when wildcards are
specified.
2020-07-10 22:17:54 -07:00
Anis Elleuch bb3c0d45f2 s3: Use list object v1 in case of GCS (#3274) 2020-06-24 06:31:59 -07:00
Harshavardhana 9ebde383d4 make sure active/active enables watch by default (#3271)
- effectively use context everywhere
- effectively look for source-mtime in all
  variations
- `mc diff` should do metadata diff as well
2020-06-23 16:57:00 -07:00
Harshavardhana cfea4fdc75 fix: overwrite is implicit with active-active (#3268)
refactor lengthy options as mirrorOptions{} for
ease of readability and usage.
2020-06-23 09:31:19 -07:00
Harshavardhana dd47bdfeaa fix: support STS for admin commands (#3264) 2020-06-19 14:31:24 -07:00
ebozduman ec9b92cbb7 Apply global context for all apis (#3240) 2020-06-19 14:31:19 -07:00
poornas 975423abe2 Fix mc cp when legal-hold or retention is set (#3257)
- Send Content-MD5 header if default retention is set on the bucket
- legal-hold needs to be case insensitive
2020-06-16 11:28:25 -07:00
Harshavardhana 3dd971f673 rename multi-master to active-active (#3255) 2020-06-15 18:18:08 -07:00
121 changed files with 857 additions and 761 deletions
+2 -3
View File
@@ -4,10 +4,9 @@ FROM arm32v7/alpine:3.12
LABEL maintainer="MinIO Inc <dev@min.io>"
COPY --from=qemu /usr/bin/qemu-arm-static /usr/bin
COPY mc /usr/bin/mc
RUN apk add --no-cache ca-certificates 'curl>7.61.0' && \
curl -s -q https://dl.minio.io/client/mc/release/linux-arm/mc -o /usr/bin/mc && \
chmod +x /usr/bin/mc && \
curl -s -q -O https://raw.githubusercontent.com/minio/minio/release/CREDITS
ENTRYPOINT ["mc"]
+4 -5
View File
@@ -1,13 +1,12 @@
FROM multiarch/qemu-user-static:x86_64-aarch64 as qemu
FROM multiarch/qemu-user-static:x86_64-arm as qemu
FROM arm64v8/alpine:3.12
LABEL maintainer="MinIO Inc <dev@min.io>"
COPY --from=qemu /usr/bin/qemu-aarch64-static /usr/bin
COPY --from=qemu /usr/bin/qemu-arm-static /usr/bin
COPY mc /usr/bin/mc
RUN apk add --no-cache ca-certificates 'curl>7.61.0' && \
curl -s -q https://dl.minio.io/client/mc/release/linux-arm64/mc -o /usr/bin/mc && \
chmod +x /usr/bin/mc && \
curl -s -q -O https://raw.githubusercontent.com/minio/minio/release/CREDITS
ENTRYPOINT ["mc"]
+4 -5
View File
@@ -1,13 +1,12 @@
FROM multiarch/qemu-user-static:x86_64-ppc64le as qemu
FROM multiarch/qemu-user-static:x86_64-arm as qemu
FROM ppc64le/alpine:3.12
LABEL maintainer="MinIO Inc <dev@min.io>"
COPY --from=qemu /usr/bin/qemu-ppc64le-static /usr/bin
COPY --from=qemu /usr/bin/qemu-arm-static /usr/bin
COPY mc /usr/bin/mc
RUN apk add --no-cache ca-certificates 'curl>7.61.0' && \
curl -s -q https://dl.minio.io/client/mc/release/linux-ppc64le/mc -o /usr/bin/mc && \
chmod +x /usr/bin/mc && \
curl -s -q -O https://raw.githubusercontent.com/minio/minio/release/CREDITS
ENTRYPOINT ["mc"]
+4 -4
View File
@@ -2,9 +2,9 @@ FROM alpine:3.12
MAINTAINER MinIO Inc <dev@min.io>
RUN apk add --no-cache ca-certificates 'curl>7.61.0' && \
curl -s -q https://dl.minio.io/client/mc/release/linux-amd64/mc -o /usr/bin/mc && \
chmod +x /usr/bin/mc && \
curl -s -q -O https://raw.githubusercontent.com/minio/minio/release/CREDITS
COPY mc /usr/bin/mc
RUN apk add --no-cache ca-certificates 'curl>7.61.0' && \
curl -s -q -O https://raw.githubusercontent.com/minio/minio/release/CREDITS
ENTRYPOINT ["mc"]
+4 -5
View File
@@ -1,13 +1,12 @@
FROM multiarch/qemu-user-static:x86_64-s390x as qemu
FROM multiarch/qemu-user-static:x86_64-arm as qemu
FROM s390x/alpine:3.12
LABEL maintainer="MinIO Inc <dev@min.io>"
COPY --from=qemu /usr/bin/qemu-s390x-static /usr/bin
COPY --from=qemu /usr/bin/qemu-arm-static /usr/bin
COPY mc /usr/bin/mc
RUN apk add --no-cache ca-certificates 'curl>7.61.0' && \
curl -s -q https://dl.minio.io/client/mc/release/linux-s390x/mc -o /usr/bin/mc && \
chmod +x /usr/bin/mc && \
curl -s -q -O https://raw.githubusercontent.com/minio/minio/release/CREDITS
ENTRYPOINT ["mc"]
+1 -1
View File
@@ -77,7 +77,7 @@ var adminBucketQuotaCmd = cli.Command{
Name: "quota",
Usage: "Manage bucket quota",
Action: mainAdminBucketQuota,
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Flags: append(adminQuotaFlags, globalFlags...),
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
-1
View File
@@ -22,7 +22,6 @@ var adminBucketCmd = cli.Command{
Name: "bucket",
Usage: "manage buckets defined in the MinIO server",
Action: mainAdminBucket,
Before: setGlobalsFromContext,
Flags: globalFlags,
Subcommands: []cli.Command{
adminBucketQuotaCmd,
+1 -1
View File
@@ -25,7 +25,7 @@ import (
var adminConfigExportCmd = cli.Command{
Name: "export",
Usage: "export all config keys to STDOUT",
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Action: mainAdminConfigExport,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
+1 -1
View File
@@ -27,7 +27,7 @@ import (
var adminConfigGetCmd = cli.Command{
Name: "get",
Usage: "interactively retrieve a config key parameters",
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Action: mainAdminConfigGet,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
+1 -1
View File
@@ -43,7 +43,7 @@ var historyListFlags = []cli.Flag{
var adminConfigHistoryCmd = cli.Command{
Name: "history",
Usage: "show all historic configuration changes",
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Action: mainAdminConfigHistory,
Flags: append(append([]cli.Flag{}, globalFlags...), historyListFlags...),
CustomHelpTemplate: `NAME:
+1 -1
View File
@@ -30,7 +30,7 @@ import (
var adminConfigImportCmd = cli.Command{
Name: "import",
Usage: "import multiple config keys from STDIN",
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Action: mainAdminConfigImport,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
+1 -1
View File
@@ -37,7 +37,7 @@ var adminConfigEnvFlags = []cli.Flag{
var adminConfigResetCmd = cli.Command{
Name: "reset",
Usage: "interactively reset a config key parameters",
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Action: mainAdminConfigReset,
Flags: append(adminConfigEnvFlags, globalFlags...),
CustomHelpTemplate: `NAME:
+1 -1
View File
@@ -29,7 +29,7 @@ import (
var adminConfigRestoreCmd = cli.Command{
Name: "restore",
Usage: "rollback back changes to a specific config history",
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Action: mainAdminConfigRestore,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
+1 -1
View File
@@ -31,7 +31,7 @@ import (
var adminConfigSetCmd = cli.Command{
Name: "set",
Usage: "interactively set a config key parameters",
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Action: mainAdminConfigSet,
Flags: append(adminConfigEnvFlags, globalFlags...),
CustomHelpTemplate: `NAME:
-1
View File
@@ -22,7 +22,6 @@ var adminConfigCmd = cli.Command{
Name: "config",
Usage: "manage MinIO server configuration",
Action: mainAdminConfig,
Before: setGlobalsFromContext,
Flags: globalFlags,
Subcommands: []cli.Command{
adminConfigGetCmd,
+1 -1
View File
@@ -49,7 +49,7 @@ var adminConsoleCmd = cli.Command{
Name: "console",
Usage: "show console logs for MinIO server",
Action: mainAdminConsole,
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Flags: append(adminConsoleFlags, globalFlags...),
HideHelpCommand: true,
CustomHelpTemplate: `NAME:
+1 -1
View File
@@ -32,7 +32,7 @@ var adminGroupAddCmd = cli.Command{
Name: "add",
Usage: "add users to a new or existing group",
Action: mainAdminGroupAdd,
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
+1 -1
View File
@@ -24,7 +24,7 @@ var adminGroupDisableCmd = cli.Command{
Name: "disable",
Usage: "Disable a group",
Action: mainAdminGroupEnableDisable,
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
+1 -1
View File
@@ -30,7 +30,7 @@ var adminGroupEnableCmd = cli.Command{
Name: "enable",
Usage: "Enable a group",
Action: mainAdminGroupEnableDisable,
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
+1 -1
View File
@@ -27,7 +27,7 @@ var adminGroupInfoCmd = cli.Command{
Name: "info",
Usage: "display group info",
Action: mainAdminGroupInfo,
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
+1 -1
View File
@@ -27,7 +27,7 @@ var adminGroupListCmd = cli.Command{
Name: "list",
Usage: "display list of groups",
Action: mainAdminGroupList,
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
+1 -1
View File
@@ -28,7 +28,7 @@ var adminGroupRemoveCmd = cli.Command{
Name: "remove",
Usage: "remove group or members from a group",
Action: mainAdminGroupRemove,
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
-1
View File
@@ -22,7 +22,6 @@ var adminGroupCmd = cli.Command{
Name: "group",
Usage: "manage groups",
Action: mainAdminGroup,
Before: setGlobalsFromContext,
Flags: globalFlags,
Subcommands: []cli.Command{
adminGroupAddCmd,
+1 -1
View File
@@ -67,7 +67,7 @@ var adminHealCmd = cli.Command{
Name: "heal",
Usage: "heal disks, buckets and objects on MinIO server",
Action: mainAdminHeal,
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Flags: append(adminHealFlags, globalFlags...),
HideHelpCommand: true,
CustomHelpTemplate: `NAME:
+1 -1
View File
@@ -38,7 +38,7 @@ var adminInfoCmd = cli.Command{
Name: "info",
Usage: "display MinIO server information",
Action: mainAdminInfo,
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
+1 -1
View File
@@ -28,7 +28,7 @@ var adminKMSKeyStatusCmd = cli.Command{
Name: "status",
Usage: "request status information for a KMS master key",
Action: mainAdminKMSKeyStatus,
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
-1
View File
@@ -22,7 +22,6 @@ var adminKMSKeyCmd = cli.Command{
Name: "key",
Usage: "Manage KMS master keys: Request key status information",
Action: mainAdminKMSKey,
Before: setGlobalsFromContext,
Flags: globalFlags,
Subcommands: []cli.Command{
adminKMSKeyStatusCmd,
-1
View File
@@ -22,7 +22,6 @@ var adminKMSCmd = cli.Command{
Name: "kms",
Usage: "perform KMS management operations",
Action: mainAdminKMS,
Before: setGlobalsFromContext,
Flags: globalFlags,
Subcommands: []cli.Command{
adminKMSKeyCmd,
-1
View File
@@ -34,7 +34,6 @@ var adminCmd = cli.Command{
Usage: "manage MinIO servers",
Action: mainAdmin,
HideHelpCommand: true,
Before: setGlobalsFromContext,
Flags: append(adminFlags, globalFlags...),
Subcommands: []cli.Command{
adminServiceCmd,
+1 -1
View File
@@ -56,7 +56,7 @@ var adminOBDCmd = cli.Command{
Name: "obd",
Usage: "run on-board diagnostics",
Action: mainAdminOBD,
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Flags: append(adminOBDFlags, globalFlags...),
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
+1 -1
View File
@@ -33,7 +33,7 @@ var adminPolicyAddCmd = cli.Command{
Name: "add",
Usage: "add new policy",
Action: mainAdminPolicyAdd,
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
+1 -1
View File
@@ -29,7 +29,7 @@ var adminPolicyInfoCmd = cli.Command{
Name: "info",
Usage: "show info on a policy",
Action: mainAdminPolicyInfo,
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
+1 -1
View File
@@ -27,7 +27,7 @@ var adminPolicyListCmd = cli.Command{
Name: "list",
Usage: "list all policies",
Action: mainAdminPolicyList,
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
+1 -1
View File
@@ -27,7 +27,7 @@ var adminPolicyRemoveCmd = cli.Command{
Name: "remove",
Usage: "remove policy",
Action: mainAdminPolicyRemove,
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
+1 -1
View File
@@ -30,7 +30,7 @@ var adminPolicySetCmd = cli.Command{
Name: "set",
Usage: "set IAM policy on a user or group",
Action: mainAdminPolicySet,
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
-1
View File
@@ -22,7 +22,6 @@ var adminPolicyCmd = cli.Command{
Name: "policy",
Usage: "manage policies defined in the MinIO server",
Action: mainAdminPolicy,
Before: setGlobalsFromContext,
Flags: globalFlags,
Subcommands: []cli.Command{
adminPolicyAddCmd,
+2 -2
View File
@@ -21,7 +21,7 @@ import (
"github.com/minio/cli"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio-go/v7/pkg/set"
"github.com/minio/minio-go/v6/pkg/set"
"github.com/minio/minio/pkg/console"
"github.com/minio/minio/pkg/madmin"
)
@@ -38,7 +38,7 @@ var adminProfileStartCmd = cli.Command{
Name: "start",
Usage: "start recording profile data",
Action: mainAdminProfileStart,
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Flags: append(adminProfileStartFlags, globalFlags...),
HideHelpCommand: true,
CustomHelpTemplate: `NAME:
+1 -1
View File
@@ -31,7 +31,7 @@ var adminProfileStopCmd = cli.Command{
Name: "stop",
Usage: "stop and download profile data",
Action: mainAdminProfileStop,
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Flags: globalFlags,
HideHelpCommand: true,
CustomHelpTemplate: `NAME:
-1
View File
@@ -24,7 +24,6 @@ var adminProfileCmd = cli.Command{
Name: "profile",
Usage: "generate profile data for debugging purposes",
Action: mainAdminProfile,
Before: setGlobalsFromContext,
Flags: globalFlags,
Subcommands: []cli.Command{
adminProfileStartCmd,
+1 -1
View File
@@ -40,7 +40,7 @@ var adminPrometheusGenerateCmd = cli.Command{
Name: "generate",
Usage: "generates prometheus config",
Action: mainAdminPrometheusGenerate,
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Flags: globalFlags,
HideHelpCommand: true,
CustomHelpTemplate: `NAME:
-1
View File
@@ -22,7 +22,6 @@ var adminPrometheusCmd = cli.Command{
Name: "prometheus",
Usage: "manages prometheus config",
Action: mainAdminPrometheus,
Before: setGlobalsFromContext,
Flags: globalFlags,
HideHelpCommand: true,
Subcommands: []cli.Command{
+1 -1
View File
@@ -30,7 +30,7 @@ var adminServiceRestartCmd = cli.Command{
Name: "restart",
Usage: "restart all MinIO servers",
Action: mainAdminServiceRestart,
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
+1 -1
View File
@@ -28,7 +28,7 @@ var adminServiceStopCmd = cli.Command{
Name: "stop",
Usage: "stop MinIO server",
Action: mainAdminServiceStop,
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
-1
View File
@@ -22,7 +22,6 @@ var adminServiceCmd = cli.Command{
Name: "service",
Usage: "restart and stop all MinIO servers",
Action: mainAdminService,
Before: setGlobalsFromContext,
Flags: globalFlags,
HideHelpCommand: true,
Subcommands: []cli.Command{
+7 -3
View File
@@ -31,7 +31,7 @@ import (
var adminTopLocksCmd = cli.Command{
Name: "locks",
Usage: "Get a list of the 10 oldest locks on a MinIO cluster.",
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Action: mainAdminTopLocks,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
@@ -75,13 +75,15 @@ func (u lockMessage) String() string {
timeFieldMaxLen := 20
resourceFieldMaxLen := -1
typeFieldMaxLen := 6
ownerFieldMaxLen := 20
lockState, timeDiff := getTimeDiff(u.Lock.Timestamp)
return console.Colorize(lockState, newPrettyTable(" ",
Field{"Time", timeFieldMaxLen},
Field{"Type", typeFieldMaxLen},
Field{"Owner", ownerFieldMaxLen},
Field{"Resource", resourceFieldMaxLen},
).buildRow(timeDiff, u.Lock.Type, u.Lock.Resource))
).buildRow(timeDiff, u.Lock.Type, u.Lock.Owner, u.Lock.Resource))
}
// JSON jsonified top oldest locks message.
@@ -128,11 +130,13 @@ func printHeaders() {
timeFieldMaxLen := 20
resourceFieldMaxLen := -1
typeFieldMaxLen := 6
ownerFieldMaxLen := 20
console.Println(console.Colorize("Headers", newPrettyTable(" ",
Field{"Time", timeFieldMaxLen},
Field{"Type", typeFieldMaxLen},
Field{"Owner", ownerFieldMaxLen},
Field{"Resource", resourceFieldMaxLen},
).buildRow("Time", "Type", "Resource")))
).buildRow("Time", "Type", "Owner", "Resource")))
}
// Prints oldest locks.
-1
View File
@@ -22,7 +22,6 @@ var adminTopCmd = cli.Command{
Name: "top",
Usage: "provide top like statistics for MinIO",
Action: mainAdminTop,
Before: setGlobalsFromContext,
Flags: globalFlags,
Subcommands: []cli.Command{
adminTopLocksCmd,
+1 -1
View File
@@ -53,7 +53,7 @@ var adminTraceCmd = cli.Command{
Name: "trace",
Usage: "show http trace for MinIO server",
Action: mainAdminTrace,
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Flags: append(adminTraceFlags, globalFlags...),
HideHelpCommand: true,
CustomHelpTemplate: `NAME:
+1 -1
View File
@@ -30,7 +30,7 @@ var adminServerUpdateCmd = cli.Command{
Name: "update",
Usage: "update all MinIO servers",
Action: mainAdminServerUpdate,
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
+1 -1
View File
@@ -34,7 +34,7 @@ var adminUserAddCmd = cli.Command{
Name: "add",
Usage: "add a new user",
Action: mainAdminUserAdd,
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
+1 -1
View File
@@ -28,7 +28,7 @@ var adminUserDisableCmd = cli.Command{
Name: "disable",
Usage: "disable user",
Action: mainAdminUserDisable,
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
+1 -1
View File
@@ -28,7 +28,7 @@ var adminUserEnableCmd = cli.Command{
Name: "enable",
Usage: "enable user",
Action: mainAdminUserEnable,
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
+1 -1
View File
@@ -27,7 +27,7 @@ var adminUserInfoCmd = cli.Command{
Name: "info",
Usage: "display info of a user",
Action: mainAdminUserInfo,
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
+1 -1
View File
@@ -27,7 +27,7 @@ var adminUserListCmd = cli.Command{
Name: "list",
Usage: "list all users",
Action: mainAdminUserList,
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
+1 -1
View File
@@ -27,7 +27,7 @@ var adminUserRemoveCmd = cli.Command{
Name: "remove",
Usage: "remove user",
Action: mainAdminUserRemove,
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
-1
View File
@@ -22,7 +22,6 @@ var adminUserCmd = cli.Command{
Name: "user",
Usage: "manage users",
Action: mainAdminUser,
Before: setGlobalsFromContext,
Flags: globalFlags,
Subcommands: []cli.Command{
adminUserAddCmd,
+1 -1
View File
@@ -44,7 +44,7 @@ var catCmd = cli.Command{
Name: "cat",
Usage: "display object contents",
Action: mainCat,
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Flags: append(append(catFlags, ioFlags...), globalFlags...),
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
+1 -1
View File
@@ -29,7 +29,7 @@ import (
"github.com/mattn/go-ieproxy"
"github.com/minio/mc/pkg/httptracer"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio-go/v7/pkg/credentials"
"github.com/minio/minio-go/v6/pkg/credentials"
"github.com/minio/minio/pkg/madmin"
)
+28 -22
View File
@@ -33,13 +33,14 @@ import (
"github.com/pkg/xattr"
"github.com/rjeczalik/notify"
"github.com/minio/mc/cmd/ilm"
"github.com/minio/mc/pkg/disk"
"github.com/minio/mc/pkg/hookreader"
"github.com/minio/mc/pkg/ioutils"
"github.com/minio/mc/pkg/probe"
minio "github.com/minio/minio-go/v7"
"github.com/minio/minio-go/v7/pkg/encrypt"
"github.com/minio/minio-go/v7/pkg/lifecycle"
minio "github.com/minio/minio-go/v6"
"github.com/minio/minio-go/v6/pkg/encrypt"
"github.com/minio/minio-go/v6/pkg/tags"
)
// filesystem client
@@ -50,7 +51,7 @@ type fsClient struct {
const (
partSuffix = ".part.minio"
slashSeperator = "/"
metadataKey = "X-Amz-Meta-Mc-Attrs"
metaDataKey = "X-Amz-Meta-Mc-Attrs"
)
var ( // GOOS specific ignore list.
@@ -274,7 +275,7 @@ func preserveAttributes(fd *os.File, attr map[string]string) *probe.Error {
/// Object operations.
func (f *fsClient) put(ctx context.Context, reader io.Reader, size int64, meta map[string]string, progress io.Reader, preserve bool) (int64, *probe.Error) {
func (f *fsClient) put(ctx context.Context, reader io.Reader, size int64, metadata map[string][]string, progress io.Reader, preserve bool) (int64, *probe.Error) {
// ContentType is not handled on purpose.
// For filesystem this is a redundant information.
@@ -310,8 +311,8 @@ func (f *fsClient) put(ctx context.Context, reader io.Reader, size int64, meta m
}
attr := make(map[string]string)
if _, ok := meta[metadataKey]; ok && preserve {
attr, e = parseAttribute(meta[metadataKey])
if len(metadata[metaDataKey]) != 0 && preserve {
attr, e = parseAttribute(metadata[metaDataKey][0])
if e != nil {
tmpFile.Close()
return 0, probe.NewError(e)
@@ -401,7 +402,12 @@ func (f *fsClient) put(ctx context.Context, reader io.Reader, size int64, meta m
// Put - create a new file with metadata.
func (f *fsClient) Put(ctx context.Context, reader io.Reader, size int64, metadata map[string]string, progress io.Reader, sse encrypt.ServerSide, md5, disableMultipart, preserve bool) (int64, *probe.Error) {
return f.put(ctx, reader, size, metadata, progress, preserve)
if metadata[metaDataKey] != "" {
meta := make(map[string][]string)
meta[metaDataKey] = append(meta[metaDataKey], metadata[metaDataKey])
return f.put(ctx, reader, size, meta, progress, preserve)
}
return f.put(ctx, reader, size, nil, progress, preserve)
}
// ShareDownload - share download not implemented for filesystem.
@@ -413,7 +419,7 @@ func (f *fsClient) ShareDownload(ctx context.Context, expires time.Duration) (st
}
// ShareUpload - share upload not implemented for filesystem.
func (f *fsClient) ShareUpload(ctx context.Context, startsWith bool, expires time.Duration, contentType string) (string, map[string]string, *probe.Error) {
func (f *fsClient) ShareUpload(startsWith bool, expires time.Duration, contentType string) (string, map[string]string, *probe.Error) {
return "", nil, probe.NewError(APINotImplemented{
API: "ShareUpload",
APIType: "filesystem",
@@ -430,7 +436,7 @@ func (f *fsClient) Copy(ctx context.Context, source string, size int64, progress
defer rc.Close()
destination := f.PathURL.Path
if _, err := f.put(ctx, rc, size, metadata, progress, preserve); err != nil {
if _, err := f.put(ctx, rc, size, map[string][]string{}, progress, preserve); err != nil {
return err.Trace(destination, source)
}
return nil
@@ -1030,6 +1036,13 @@ func (f *fsClient) Stat(ctx context.Context, isIncomplete, isPreserve bool, sse
}
path := f.PathURL.String()
metaData, pErr := getAllXattrs(path)
if pErr != nil {
return content, nil
}
for k, v := range metaData {
content.Metadata[k] = v
}
// Populates meta data with file system attribute only in case of
// when preserve flag is passed.
if isPreserve {
@@ -1037,14 +1050,7 @@ func (f *fsClient) Stat(ctx context.Context, isIncomplete, isPreserve bool, sse
if err != nil {
return content, nil
}
metaData, pErr := getAllXattrs(path)
if pErr != nil {
return content, nil
}
for k, v := range metaData {
content.Metadata[k] = v
}
content.Metadata[metadataKey] = fileAttr
content.Metadata[metaDataKey] = fileAttr
}
return content, nil
@@ -1090,7 +1096,7 @@ func (f *fsClient) AddUserAgent(_, _ string) {
}
// Get Object Tags
func (f *fsClient) GetTags(ctx context.Context) (map[string]string, *probe.Error) {
func (f *fsClient) GetTags(ctx context.Context) (*tags.Tags, *probe.Error) {
return nil, probe.NewError(APINotImplemented{
API: "GetObjectTagging",
APIType: "filesystem",
@@ -1114,15 +1120,15 @@ func (f *fsClient) DeleteTags(ctx context.Context) *probe.Error {
}
// Get lifecycle configuration for a given bucket, not implemented.
func (f *fsClient) GetLifecycle(ctx context.Context) (*lifecycle.Configuration, *probe.Error) {
return nil, probe.NewError(APINotImplemented{
func (f *fsClient) GetLifecycle(ctx context.Context) (ilm.LifecycleConfiguration, *probe.Error) {
return ilm.LifecycleConfiguration{}, probe.NewError(APINotImplemented{
API: "GetLifecycle",
APIType: "filesystem",
})
}
// Set lifecycle configuration for a given bucket, not implemented.
func (f *fsClient) SetLifecycle(ctx context.Context, _ *lifecycle.Configuration) *probe.Error {
func (f *fsClient) SetLifecycle(ctx context.Context, _ ilm.LifecycleConfiguration) *probe.Error {
return probe.NewError(APINotImplemented{
API: "SetLifecycle",
APIType: "filesystem",
+151 -126
View File
@@ -21,6 +21,7 @@ import (
"context"
"crypto/tls"
"encoding/json"
"encoding/xml"
"errors"
"fmt"
"hash/fnv"
@@ -36,16 +37,16 @@ import (
"sync"
"time"
"github.com/mattn/go-ieproxy"
"github.com/minio/mc/cmd/ilm"
"github.com/minio/mc/pkg/httptracer"
"github.com/minio/mc/pkg/probe"
minio "github.com/minio/minio-go/v7"
"github.com/minio/minio-go/v7/pkg/credentials"
"github.com/minio/minio-go/v7/pkg/encrypt"
"github.com/minio/minio-go/v7/pkg/lifecycle"
"github.com/minio/minio-go/v7/pkg/notification"
"github.com/minio/minio-go/v7/pkg/policy"
"github.com/minio/minio-go/v7/pkg/s3utils"
"github.com/minio/minio-go/v7/pkg/tags"
minio "github.com/minio/minio-go/v6"
"github.com/minio/minio-go/v6/pkg/credentials"
"github.com/minio/minio-go/v6/pkg/encrypt"
"github.com/minio/minio-go/v6/pkg/policy"
"github.com/minio/minio-go/v6/pkg/s3utils"
"github.com/minio/minio-go/v6/pkg/tags"
"github.com/minio/minio/pkg/mimedb"
)
@@ -149,7 +150,7 @@ func newFactory() func(config *Config) (Client, *probe.Error) {
}
tr := &http.Transport{
Proxy: http.ProxyFromEnvironment,
Proxy: ieproxy.GetProxyFunc(),
DialContext: (&net.Dialer{
Timeout: 10 * time.Second,
KeepAlive: 15 * time.Second,
@@ -241,23 +242,23 @@ func (c *S3Client) AddNotificationConfig(ctx context.Context, arn string, events
}
// Get any enabled notification.
mb, e := c.api.GetBucketNotification(ctx, bucket)
mb, e := c.api.GetBucketNotificationWithContext(ctx, bucket)
if e != nil {
return probe.NewError(e)
}
accountArn := notification.NewArn(fields[1], fields[2], fields[3], fields[4], fields[5])
nc := notification.NewConfig(accountArn)
accountArn := minio.NewArn(fields[1], fields[2], fields[3], fields[4], fields[5])
nc := minio.NewNotificationConfig(accountArn)
// Configure events
for _, event := range events {
switch event {
case "put":
nc.AddEvents(notification.ObjectCreatedAll)
nc.AddEvents(minio.ObjectCreatedAll)
case "delete":
nc.AddEvents(notification.ObjectRemovedAll)
nc.AddEvents(minio.ObjectRemovedAll)
case "get":
nc.AddEvents(notification.ObjectAccessedAll)
nc.AddEvents(minio.ObjectAccessedAll)
default:
return errInvalidArgument().Trace(events...)
}
@@ -287,7 +288,7 @@ func (c *S3Client) AddNotificationConfig(ctx context.Context, arn string, events
}
// Set the new bucket configuration
if err := c.api.SetBucketNotification(ctx, bucket, mb); err != nil {
if err := c.api.SetBucketNotification(bucket, mb); err != nil {
if ignoreExisting && strings.Contains(err.Error(), "An object key name filtering rule defined with overlapping prefixes, overlapping suffixes, or overlapping combinations of prefixes and suffixes for the same event types") {
return nil
}
@@ -301,13 +302,13 @@ func (c *S3Client) RemoveNotificationConfig(ctx context.Context, arn string, eve
bucket, _ := c.url2BucketAndObject()
// Remove all notification configs if arn is empty
if arn == "" {
if err := c.api.RemoveAllBucketNotification(ctx, bucket); err != nil {
if err := c.api.RemoveAllBucketNotificationWithContext(ctx, bucket); err != nil {
return probe.NewError(err)
}
return nil
}
mb, e := c.api.GetBucketNotification(ctx, bucket)
mb, e := c.api.GetBucketNotificationWithContext(ctx, bucket)
if e != nil {
return probe.NewError(e)
}
@@ -316,22 +317,22 @@ func (c *S3Client) RemoveNotificationConfig(ctx context.Context, arn string, eve
if len(fields) != 6 {
return errInvalidArgument().Trace(fields...)
}
accountArn := notification.NewArn(fields[1], fields[2], fields[3], fields[4], fields[5])
accountArn := minio.NewArn(fields[1], fields[2], fields[3], fields[4], fields[5])
// if we are passed filters for either events, suffix or prefix, then only delete the single event that matches
// the arguments
if event != "" || suffix != "" || prefix != "" {
// Translate events to type events for comparison
events := strings.Split(event, ",")
var eventsTyped []notification.EventType
var eventsTyped []minio.NotificationEventType
for _, e := range events {
switch e {
case "put":
eventsTyped = append(eventsTyped, notification.ObjectCreatedAll)
eventsTyped = append(eventsTyped, minio.ObjectCreatedAll)
case "delete":
eventsTyped = append(eventsTyped, notification.ObjectRemovedAll)
eventsTyped = append(eventsTyped, minio.ObjectRemovedAll)
case "get":
eventsTyped = append(eventsTyped, notification.ObjectAccessedAll)
eventsTyped = append(eventsTyped, minio.ObjectAccessedAll)
default:
return errInvalidArgument().Trace(events...)
}
@@ -367,7 +368,7 @@ func (c *S3Client) RemoveNotificationConfig(ctx context.Context, arn string, eve
}
// Set the new bucket configuration
if e := c.api.SetBucketNotification(ctx, bucket, mb); e != nil {
if e := c.api.SetBucketNotification(bucket, mb); e != nil {
return probe.NewError(e)
}
return nil
@@ -386,13 +387,13 @@ type NotificationConfig struct {
func (c *S3Client) ListNotificationConfigs(ctx context.Context, arn string) ([]NotificationConfig, *probe.Error) {
var configs []NotificationConfig
bucket, _ := c.url2BucketAndObject()
mb, e := c.api.GetBucketNotification(ctx, bucket)
mb, e := c.api.GetBucketNotificationWithContext(ctx, bucket)
if e != nil {
return nil, probe.NewError(e)
}
// Generate pretty event names from event types
prettyEventNames := func(eventsTypes []notification.EventType) []string {
prettyEventNames := func(eventsTypes []minio.NotificationEventType) []string {
var result []string
for _, eventType := range eventsTypes {
result = append(result, string(eventType))
@@ -400,7 +401,7 @@ func (c *S3Client) ListNotificationConfigs(ctx context.Context, arn string) ([]N
return result
}
getFilters := func(config notification.Config) (prefix, suffix string) {
getFilters := func(config minio.NotificationConfig) (prefix, suffix string) {
if config.Filter == nil {
return
}
@@ -420,7 +421,7 @@ func (c *S3Client) ListNotificationConfigs(ctx context.Context, arn string) ([]N
if arn != "" && config.Topic != arn {
continue
}
prefix, suffix := getFilters(config.Config)
prefix, suffix := getFilters(config.NotificationConfig)
configs = append(configs, NotificationConfig{ID: config.ID,
Arn: config.Topic,
Events: prettyEventNames(config.Events),
@@ -432,7 +433,7 @@ func (c *S3Client) ListNotificationConfigs(ctx context.Context, arn string) ([]N
if arn != "" && config.Queue != arn {
continue
}
prefix, suffix := getFilters(config.Config)
prefix, suffix := getFilters(config.NotificationConfig)
configs = append(configs, NotificationConfig{ID: config.ID,
Arn: config.Queue,
Events: prettyEventNames(config.Events),
@@ -444,7 +445,7 @@ func (c *S3Client) ListNotificationConfigs(ctx context.Context, arn string) ([]N
if arn != "" && config.Lambda != arn {
continue
}
prefix, suffix := getFilters(config.Config)
prefix, suffix := getFilters(config.NotificationConfig)
configs = append(configs, NotificationConfig{ID: config.ID,
Arn: config.Lambda,
Events: prettyEventNames(config.Events),
@@ -626,7 +627,7 @@ func (c *S3Client) Select(ctx context.Context, expression string, sse encrypt.Se
return reader, nil
}
func (c *S3Client) notificationToEventsInfo(ninfo notification.Info) []EventInfo {
func (c *S3Client) notificationToEventsInfo(ninfo minio.NotificationInfo) []EventInfo {
var eventsInfo = make([]EventInfo, len(ninfo.Records))
for i, record := range ninfo.Records {
bucketName := record.S3.Bucket.Name
@@ -700,7 +701,7 @@ func (c *S3Client) notificationToEventsInfo(ninfo notification.Info) []EventInfo
Port: record.Source.Port,
UserAgent: record.Source.UserAgent,
}
} else if record.EventName == notification.ObjectAccessedGet {
} else if record.EventName == minio.ObjectAccessedGet {
eventsInfo[i] = EventInfo{
Time: record.EventTime,
Size: record.S3.Object.Size,
@@ -711,7 +712,7 @@ func (c *S3Client) notificationToEventsInfo(ninfo notification.Info) []EventInfo
Port: record.Source.Port,
UserAgent: record.Source.UserAgent,
}
} else if record.EventName == notification.ObjectAccessedHead {
} else if record.EventName == minio.ObjectAccessedHead {
eventsInfo[i] = EventInfo{
Time: record.EventTime,
Size: record.S3.Object.Size,
@@ -737,11 +738,11 @@ func (c *S3Client) Watch(ctx context.Context, options WatchOptions) (*WatchObjec
for _, event := range options.Events {
switch event {
case "put":
events = append(events, string(notification.ObjectCreatedAll))
events = append(events, string(minio.ObjectCreatedAll))
case "delete":
events = append(events, string(notification.ObjectRemovedAll))
events = append(events, string(minio.ObjectRemovedAll))
case "get":
events = append(events, string(notification.ObjectAccessedAll))
events = append(events, string(minio.ObjectAccessedAll))
default:
return nil, errInvalidArgument().Trace(event)
}
@@ -756,7 +757,7 @@ func (c *S3Client) Watch(ctx context.Context, options WatchOptions) (*WatchObjec
// The list of buckets to watch
var buckets []string
if bucket == "" {
bkts, err := c.api.ListBuckets(ctx)
bkts, err := c.api.ListBucketsWithContext(ctx)
if err != nil {
return nil, probe.NewError(err)
}
@@ -780,7 +781,7 @@ func (c *S3Client) Watch(ctx context.Context, options WatchOptions) (*WatchObjec
go func() {
defer wg.Done()
// Start listening on all bucket events.
eventsCh := c.api.ListenBucketNotification(ctx, bucket, options.Prefix, options.Suffix, events)
eventsCh := c.api.ListenBucketNotificationWithContext(ctx, bucket, options.Prefix, options.Suffix, events, wo.DoneChan)
for notificationInfo := range eventsCh {
if notificationInfo.Err != nil {
var perr *probe.Error
@@ -815,7 +816,7 @@ func (c *S3Client) Get(ctx context.Context, sse encrypt.ServerSide) (io.ReadClos
bucket, object := c.url2BucketAndObject()
opts := minio.GetObjectOptions{}
opts.ServerSideEncryption = sse
reader, e := c.api.GetObject(ctx, bucket, object, opts)
reader, e := c.api.GetObjectWithContext(ctx, bucket, object, opts)
if e != nil {
errResponse := minio.ToErrorResponse(e)
if errResponse.Code == "NoSuchBucket" {
@@ -848,18 +849,10 @@ func (c *S3Client) Copy(ctx context.Context, source string, size int64, progress
tokens := splitStr(source, string(c.targetURL.Separator), 3)
// Source object
srcOpts := minio.CopySrcOptions{
Bucket: tokens[1],
Object: tokens[2],
Encryption: srcSSE,
}
src := minio.NewSourceInfo(tokens[1], tokens[2], srcSSE)
destOpts := minio.CopyDestOptions{
Bucket: dstBucket,
Object: dstObject,
destOpts := minio.DestInfoOptions{
Encryption: tgtSSE,
Progress: progress,
Size: size,
}
if lockModeStr, ok := metadata[AmzObjectLockMode]; ok {
@@ -880,13 +873,18 @@ func (c *S3Client) Copy(ctx context.Context, source string, size int64, progress
}
// Assign metadata after irrelevant parts are delete above
destOpts.UserMetadata = metadata
destOpts.UserMeta = metadata
var e error
if disableMultipart || size < 64*1024*1024 {
_, e = c.api.CopyObject(ctx, destOpts, srcOpts)
// Destination object
dst, e := minio.NewDestinationInfoWithOptions(dstBucket, dstObject, destOpts)
if e != nil {
return probe.NewError(e)
}
if disableMultipart {
e = c.api.CopyObjectWithProgressWithContext(ctx, dst, src, progress)
} else {
_, e = c.api.ComposeObject(ctx, destOpts, srcOpts)
e = c.api.ComposeObjectWithProgressWithContext(ctx, dst, []minio.SourceInfo{src}, progress)
}
if e != nil {
@@ -985,11 +983,11 @@ func (c *S3Client) Put(ctx context.Context, reader io.Reader, size int64, metada
}
if !retainUntilDate.IsZero() && !retainUntilDate.Equal(timeSentinel) {
opts.RetainUntilDate = retainUntilDate
opts.RetainUntilDate = &retainUntilDate
}
if lockModeStr != "" {
opts.Mode = lockMode
opts.Mode = &lockMode
opts.SendContentMd5 = true
}
@@ -998,51 +996,51 @@ func (c *S3Client) Put(ctx context.Context, reader io.Reader, size int64, metada
opts.LegalHold = minio.LegalHoldStatus(strings.ToUpper(lh))
opts.SendContentMd5 = true
}
if opts.LegalHold == "" && opts.Mode == "" {
if _, _, _, err := c.api.GetBucketObjectLockConfig(ctx, bucket); err == nil {
if opts.LegalHold == "" && opts.Mode == nil {
if _, _, _, err := c.api.GetBucketObjectLockConfig(bucket); err == nil {
opts.SendContentMd5 = true
}
}
ui, e := c.api.PutObject(ctx, bucket, object, reader, size, opts)
n, e := c.api.PutObjectWithContext(ctx, bucket, object, reader, size, opts)
if e != nil {
errResponse := minio.ToErrorResponse(e)
if errResponse.Code == "UnexpectedEOF" || e == io.EOF {
return ui.Size, probe.NewError(UnexpectedEOF{
return n, probe.NewError(UnexpectedEOF{
TotalSize: size,
TotalWritten: ui.Size,
TotalWritten: n,
})
}
if errResponse.Code == "AccessDenied" {
return ui.Size, probe.NewError(PathInsufficientPermission{
return n, probe.NewError(PathInsufficientPermission{
Path: c.targetURL.String(),
})
}
if errResponse.Code == "MethodNotAllowed" {
return ui.Size, probe.NewError(ObjectAlreadyExists{
return n, probe.NewError(ObjectAlreadyExists{
Object: object,
})
}
if errResponse.Code == "XMinioObjectExistsAsDirectory" {
return ui.Size, probe.NewError(ObjectAlreadyExistsAsDirectory{
return n, probe.NewError(ObjectAlreadyExistsAsDirectory{
Object: object,
})
}
if errResponse.Code == "NoSuchBucket" {
return ui.Size, probe.NewError(BucketDoesNotExist{
return n, probe.NewError(BucketDoesNotExist{
Bucket: bucket,
})
}
if errResponse.Code == "InvalidBucketName" {
return ui.Size, probe.NewError(BucketInvalid{
return n, probe.NewError(BucketInvalid{
Bucket: bucket,
})
}
if errResponse.Code == "NoSuchKey" {
return ui.Size, probe.NewError(ObjectMissing{})
return n, probe.NewError(ObjectMissing{})
}
return ui.Size, probe.NewError(e)
return n, probe.NewError(e)
}
return ui.Size, nil
return n, nil
}
// Remove incomplete uploads.
@@ -1054,7 +1052,7 @@ func (c *S3Client) removeIncompleteObjects(ctx context.Context, bucket string, o
defer close(removeObjectErrorCh)
for object := range objectsCh {
if err := c.api.RemoveIncompleteUpload(ctx, bucket, object); err != nil {
if err := c.api.RemoveIncompleteUploadWithContext(ctx, bucket, object); err != nil {
removeObjectErrorCh <- minio.RemoveObjectError{ObjectName: object, Err: err}
}
}
@@ -1105,7 +1103,7 @@ func (c *S3Client) Remove(ctx context.Context, isIncomplete, isRemoveBucket, isB
if isIncomplete {
statusCh = c.removeIncompleteObjects(ctx, bucket, objectsCh)
} else {
statusCh = c.api.RemoveObjects(ctx, bucket, objectsCh, opts)
statusCh = c.api.RemoveObjectsWithOptionsContext(ctx, bucket, objectsCh, opts)
}
}
@@ -1118,7 +1116,7 @@ func (c *S3Client) Remove(ctx context.Context, isIncomplete, isRemoveBucket, isB
}
// Remove bucket if it qualifies.
if isRemoveBucket && !isIncomplete {
if err := c.api.RemoveBucket(ctx, prevBucket); err != nil {
if err := c.api.RemoveBucketWithContext(ctx, prevBucket); err != nil {
errorCh <- probe.NewError(err)
}
}
@@ -1127,7 +1125,7 @@ func (c *S3Client) Remove(ctx context.Context, isIncomplete, isRemoveBucket, isB
if isIncomplete {
statusCh = c.removeIncompleteObjects(ctx, bucket, objectsCh)
} else {
statusCh = c.api.RemoveObjects(ctx, bucket, objectsCh, opts)
statusCh = c.api.RemoveObjectsWithOptionsContext(ctx, bucket, objectsCh, opts)
}
prevBucket = bucket
}
@@ -1165,7 +1163,7 @@ func (c *S3Client) Remove(ctx context.Context, isIncomplete, isRemoveBucket, isB
}
// Remove last bucket if it qualifies.
if isRemoveBucket && prevBucket != "" && !isIncomplete {
if err := c.api.RemoveBucket(ctx, prevBucket); err != nil {
if err := c.api.RemoveBucketWithContext(ctx, prevBucket); err != nil {
errorCh <- probe.NewError(err)
}
}
@@ -1188,7 +1186,7 @@ func (c *S3Client) MakeBucket(ctx context.Context, region string, ignoreExisting
}
var retried bool
for {
_, e := c.api.PutObject(ctx, bucket, object,
_, e := c.api.PutObjectWithContext(ctx, bucket, object,
bytes.NewReader([]byte("")), 0, minio.PutObjectOptions{})
if e == nil {
return nil
@@ -1198,8 +1196,12 @@ func (c *S3Client) MakeBucket(ctx context.Context, region string, ignoreExisting
}
switch minio.ToErrorResponse(e).Code {
case "NoSuchBucket":
opts := minio.MakeBucketOptions{Region: region, ObjectLocking: withLock}
if e = c.api.MakeBucket(ctx, bucket, opts); e != nil {
if withLock {
e = c.api.MakeBucketWithObjectLockWithContext(ctx, bucket, region)
} else {
e = c.api.MakeBucketWithContext(ctx, bucket, region)
}
if e != nil {
return probe.NewError(e)
}
retried = true
@@ -1210,8 +1212,12 @@ func (c *S3Client) MakeBucket(ctx context.Context, region string, ignoreExisting
}
var e error
opts := minio.MakeBucketOptions{Region: region, ObjectLocking: withLock}
if e = c.api.MakeBucket(ctx, bucket, opts); e != nil {
if withLock {
e = c.api.MakeBucketWithObjectLockWithContext(ctx, bucket, region)
} else {
e = c.api.MakeBucketWithContext(ctx, bucket, region)
}
if e != nil {
// Ignore bucket already existing error when ignoreExisting flag is enabled
if ignoreExisting {
switch minio.ToErrorResponse(e).Code {
@@ -1233,7 +1239,7 @@ func (c *S3Client) GetAccessRules(ctx context.Context) (map[string]string, *prob
return map[string]string{}, probe.NewError(BucketNameEmpty{})
}
policies := map[string]string{}
policyStr, e := c.api.GetBucketPolicy(ctx, bucket)
policyStr, e := c.api.GetBucketPolicyWithContext(ctx, bucket)
if e != nil {
return nil, probe.NewError(e)
}
@@ -1258,7 +1264,7 @@ func (c *S3Client) GetAccess(ctx context.Context) (string, string, *probe.Error)
if bucket == "" {
return "", "", probe.NewError(BucketNameEmpty{})
}
policyStr, e := c.api.GetBucketPolicy(ctx, bucket)
policyStr, e := c.api.GetBucketPolicyWithContext(ctx, bucket)
if e != nil {
return "", "", probe.NewError(e)
}
@@ -1283,12 +1289,12 @@ func (c *S3Client) SetAccess(ctx context.Context, bucketPolicy string, isJSON bo
return probe.NewError(BucketNameEmpty{})
}
if isJSON {
if e := c.api.SetBucketPolicy(ctx, bucket, bucketPolicy); e != nil {
if e := c.api.SetBucketPolicyWithContext(ctx, bucket, bucketPolicy); e != nil {
return probe.NewError(e)
}
return nil
}
policyStr, e := c.api.GetBucketPolicy(ctx, bucket)
policyStr, e := c.api.GetBucketPolicyWithContext(ctx, bucket)
if e != nil {
return probe.NewError(e)
}
@@ -1300,7 +1306,7 @@ func (c *S3Client) SetAccess(ctx context.Context, bucketPolicy string, isJSON bo
}
p.Statements = policy.SetPolicy(p.Statements, policy.BucketPolicy(bucketPolicy), bucket, object)
if len(p.Statements) == 0 {
if e = c.api.SetBucketPolicy(ctx, bucket, ""); e != nil {
if e = c.api.SetBucketPolicyWithContext(ctx, bucket, ""); e != nil {
return probe.NewError(e)
}
return nil
@@ -1309,7 +1315,7 @@ func (c *S3Client) SetAccess(ctx context.Context, bucketPolicy string, isJSON bo
if e != nil {
return probe.NewError(e)
}
if e = c.api.SetBucketPolicy(ctx, bucket, string(policyB)); e != nil {
if e = c.api.SetBucketPolicyWithContext(ctx, bucket, string(policyB)); e != nil {
return probe.NewError(e)
}
return nil
@@ -1320,12 +1326,12 @@ func (c *S3Client) listObjectWrapper(ctx context.Context, bucket, object string,
if isGoogle(c.targetURL.Host) {
// Google Cloud S3 layer doesn't implement ListObjectsV2 implementation
// https://github.com/minio/mc/issues/3073
return c.api.ListObjects(ctx, bucket, minio.ListObjectsOptions{Prefix: object, Recursive: isRecursive, UseV1: true})
return c.api.ListObjectsWithContext(ctx, bucket, object, isRecursive, doneCh)
}
if metadata {
return c.api.ListObjects(ctx, bucket, minio.ListObjectsOptions{Prefix: object, Recursive: isRecursive})
return c.api.ListObjectsV2WithMetadataWithContext(ctx, bucket, object, isRecursive, doneCh)
}
return c.api.ListObjects(ctx, bucket, minio.ListObjectsOptions{Prefix: object, Recursive: isRecursive})
return c.api.ListObjectsV2WithContext(ctx, bucket, object, isRecursive, doneCh)
}
func (c *S3Client) statIncompleteUpload(ctx context.Context, bucket, object string) (*ClientContent, *probe.Error) {
@@ -1334,7 +1340,7 @@ func (c *S3Client) statIncompleteUpload(ctx context.Context, bucket, object stri
// Prefix to pass to minio-go listing in order to fetch a given object/directory
prefix := strings.TrimRight(object, string(c.targetURL.Separator))
for objectMultipartInfo := range c.api.ListIncompleteUploads(ctx, bucket, prefix, nonRecursive) {
for objectMultipartInfo := range c.api.ListIncompleteUploadsWithContext(ctx, bucket, prefix, nonRecursive, nil) {
if objectMultipartInfo.Err != nil {
return nil, probe.NewError(objectMultipartInfo.Err)
}
@@ -1429,7 +1435,7 @@ func (c *S3Client) Stat(ctx context.Context, isIncomplete, isPreserve bool, sse
// getObjectStat returns the metadata of an object from a HEAD call.
func (c *S3Client) getObjectStat(ctx context.Context, bucket, object string, opts minio.StatObjectOptions) (*ClientContent, *probe.Error) {
objectStat, e := c.api.StatObject(ctx, bucket, object, opts)
objectStat, e := c.api.StatObjectWithContext(ctx, bucket, object, opts)
if e != nil {
errResponse := minio.ToErrorResponse(e)
if errResponse.Code == "AccessDenied" {
@@ -1579,7 +1585,7 @@ func (c *S3Client) listIncompleteInRoutine(ctx context.Context, contentCh chan *
b, o := c.url2BucketAndObject()
switch {
case b == "" && o == "":
buckets, err := c.api.ListBuckets(ctx)
buckets, err := c.api.ListBucketsWithContext(ctx)
if err != nil {
contentCh <- &ClientContent{
Err: probe.NewError(err),
@@ -1588,7 +1594,7 @@ func (c *S3Client) listIncompleteInRoutine(ctx context.Context, contentCh chan *
}
isRecursive := false
for _, bucket := range buckets {
for object := range c.api.ListIncompleteUploads(ctx, bucket.Name, o, isRecursive) {
for object := range c.api.ListIncompleteUploadsWithContext(ctx, bucket.Name, o, isRecursive, nil) {
if object.Err != nil {
contentCh <- &ClientContent{
Err: probe.NewError(object.Err),
@@ -1616,7 +1622,7 @@ func (c *S3Client) listIncompleteInRoutine(ctx context.Context, contentCh chan *
}
default:
isRecursive := false
for object := range c.api.ListIncompleteUploads(ctx, b, o, isRecursive) {
for object := range c.api.ListIncompleteUploadsWithContext(ctx, b, o, isRecursive, nil) {
if object.Err != nil {
contentCh <- &ClientContent{
Err: probe.NewError(object.Err),
@@ -1650,7 +1656,7 @@ func (c *S3Client) listIncompleteRecursiveInRoutine(ctx context.Context, content
b, o := c.url2BucketAndObject()
switch {
case b == "" && o == "":
buckets, err := c.api.ListBuckets(ctx)
buckets, err := c.api.ListBucketsWithContext(ctx)
if err != nil {
contentCh <- &ClientContent{
Err: probe.NewError(err),
@@ -1659,7 +1665,7 @@ func (c *S3Client) listIncompleteRecursiveInRoutine(ctx context.Context, content
}
isRecursive := true
for _, bucket := range buckets {
for object := range c.api.ListIncompleteUploads(ctx, bucket.Name, o, isRecursive) {
for object := range c.api.ListIncompleteUploadsWithContext(ctx, bucket.Name, o, isRecursive, nil) {
if object.Err != nil {
contentCh <- &ClientContent{
Err: probe.NewError(object.Err),
@@ -1678,7 +1684,7 @@ func (c *S3Client) listIncompleteRecursiveInRoutine(ctx context.Context, content
}
default:
isRecursive := true
for object := range c.api.ListIncompleteUploads(ctx, b, o, isRecursive) {
for object := range c.api.ListIncompleteUploadsWithContext(ctx, b, o, isRecursive, nil) {
if object.Err != nil {
contentCh <- &ClientContent{
Err: probe.NewError(object.Err),
@@ -1727,7 +1733,7 @@ func (c *S3Client) listIncompleteRecursiveInRoutineDirOpt(ctx context.Context, c
var listDir func(bucket, object string) bool
listDir = func(bucket, object string) (isStop bool) {
isRecursive := false
for entry := range c.api.ListIncompleteUploads(ctx, bucket, object, isRecursive) {
for entry := range c.api.ListIncompleteUploadsWithContext(ctx, bucket, object, isRecursive, nil) {
if entry.Err != nil {
url := c.targetURL.Clone()
url.Path = c.joinPath(bucket, object)
@@ -1770,7 +1776,7 @@ func (c *S3Client) listIncompleteRecursiveInRoutineDirOpt(ctx context.Context, c
if bucket == "" && object == "" {
var e error
allBuckets = true
buckets, e = c.api.ListBuckets(ctx)
buckets, e = c.api.ListBucketsWithContext(ctx)
if e != nil {
contentCh <- &ClientContent{Err: probe.NewError(e)}
return
@@ -1868,7 +1874,7 @@ func (c *S3Client) objectInfo2ClientContent(bucket string, entry minio.ObjectInf
// Returns bucket stat info of current bucket.
func (c *S3Client) bucketStat(ctx context.Context, bucket string) (*ClientContent, *probe.Error) {
exists, e := c.api.BucketExists(ctx, bucket)
exists, e := c.api.BucketExistsWithContext(ctx, bucket)
if e != nil {
return nil, probe.NewError(e)
}
@@ -1928,7 +1934,7 @@ func (c *S3Client) listRecursiveInRoutineDirOpt(ctx context.Context, contentCh c
if bucket == "" && object == "" {
var e error
allBuckets = true
buckets, e = c.api.ListBuckets(ctx)
buckets, e = c.api.ListBucketsWithContext(ctx)
if e != nil {
contentCh <- &ClientContent{Err: probe.NewError(e)}
return
@@ -1975,7 +1981,7 @@ func (c *S3Client) listInRoutine(ctx context.Context, contentCh chan *ClientCont
b, o := c.url2BucketAndObject()
switch {
case b == "" && o == "":
buckets, e := c.api.ListBuckets(ctx)
buckets, e := c.api.ListBucketsWithContext(ctx)
if e != nil {
contentCh <- &ClientContent{
Err: probe.NewError(e),
@@ -2031,7 +2037,7 @@ func (c *S3Client) listRecursiveInRoutine(ctx context.Context, contentCh chan *C
b, o := c.url2BucketAndObject()
switch {
case b == "" && o == "":
buckets, err := c.api.ListBuckets(ctx)
buckets, err := c.api.ListBucketsWithContext(ctx)
if err != nil {
contentCh <- &ClientContent{
Err: probe.NewError(err),
@@ -2069,7 +2075,7 @@ func (c *S3Client) ShareDownload(ctx context.Context, expires time.Duration) (st
bucket, object := c.url2BucketAndObject()
// No additional request parameters are set for the time being.
reqParams := make(url.Values)
presignedURL, e := c.api.PresignedGetObject(ctx, bucket, object, expires, reqParams)
presignedURL, e := c.api.PresignedGetObjectWithContext(ctx, bucket, object, expires, reqParams)
if e != nil {
return "", probe.NewError(e)
}
@@ -2077,7 +2083,7 @@ func (c *S3Client) ShareDownload(ctx context.Context, expires time.Duration) (st
}
// ShareUpload - get data for presigned post http form upload.
func (c *S3Client) ShareUpload(ctx context.Context, isRecursive bool, expires time.Duration, contentType string) (string, map[string]string, *probe.Error) {
func (c *S3Client) ShareUpload(isRecursive bool, expires time.Duration, contentType string) (string, map[string]string, *probe.Error) {
bucket, object := c.url2BucketAndObject()
p := minio.NewPostPolicy()
if e := p.SetExpires(UTCNow().Add(expires)); e != nil {
@@ -2099,7 +2105,7 @@ func (c *S3Client) ShareUpload(ctx context.Context, isRecursive bool, expires ti
return "", nil, probe.NewError(e)
}
}
u, m, e := c.api.PresignedPostPolicy(ctx, p)
u, m, e := c.api.PresignedPostPolicy(p)
if e != nil {
return "", nil, probe.NewError(e)
}
@@ -2113,14 +2119,14 @@ func (c *S3Client) SetObjectLockConfig(ctx context.Context, mode minio.Retention
// FIXME: This is too ugly, fix minio-go
vuint := (uint)(validity)
if mode != "" && vuint > 0 && unit != "" {
e := c.api.SetBucketObjectLockConfig(ctx, bucket, &mode, &vuint, &unit)
e := c.api.SetBucketObjectLockConfigWithContext(ctx, bucket, &mode, &vuint, &unit)
if e != nil {
return probe.NewError(e).Trace(c.GetURL().String())
}
return nil
}
if mode == "" && vuint == 0 && unit == "" {
e := c.api.SetBucketObjectLockConfig(ctx, bucket, nil, nil, nil)
e := c.api.SetBucketObjectLockConfigWithContext(ctx, bucket, nil, nil, nil)
if e != nil {
return probe.NewError(e).Trace(c.GetURL().String())
}
@@ -2139,7 +2145,7 @@ func (c *S3Client) PutObjectRetention(ctx context.Context, mode minio.RetentionM
Mode: &mode,
GovernanceBypass: bypassGovernance,
}
e := c.api.PutObjectRetention(ctx, bucket, object, opts)
e := c.api.PutObjectRetentionWithContext(ctx, bucket, object, opts)
if e != nil {
return probe.NewError(e).Trace(c.GetURL().String())
}
@@ -2156,7 +2162,7 @@ func (c *S3Client) PutObjectLegalHold(ctx context.Context, lhold minio.LegalHold
opts := minio.PutObjectLegalHoldOptions{
Status: &lhold,
}
e := c.api.PutObjectLegalHold(ctx, bucket, object, opts)
e := c.api.PutObjectLegalHoldWithContext(ctx, bucket, object, opts)
if e != nil {
return probe.NewError(e).Trace(c.GetURL().String())
}
@@ -2169,7 +2175,7 @@ func (c *S3Client) PutObjectLegalHold(ctx context.Context, lhold minio.LegalHold
func (c *S3Client) GetObjectLockConfig(ctx context.Context) (minio.RetentionMode, uint64, minio.ValidityUnit, *probe.Error) {
bucket, _ := c.url2BucketAndObject()
mode, validity, unit, e := c.api.GetBucketObjectLockConfig(ctx, bucket)
mode, validity, unit, e := c.api.GetBucketObjectLockConfigWithContext(ctx, bucket)
if e != nil {
return "", 0, "", probe.NewError(e).Trace(c.GetURL().String())
}
@@ -2184,27 +2190,32 @@ func (c *S3Client) GetObjectLockConfig(ctx context.Context) (minio.RetentionMode
}
// GetTags - Get tags of bucket or object.
func (c *S3Client) GetTags(ctx context.Context) (map[string]string, *probe.Error) {
func (c *S3Client) GetTags(ctx context.Context) (*tags.Tags, *probe.Error) {
bucketName, objectName := c.url2BucketAndObject()
if bucketName == "" {
return nil, probe.NewError(BucketNameEmpty{})
}
if objectName == "" {
tags, err := c.api.GetBucketTagging(ctx, bucketName)
tags, err := c.api.GetBucketTaggingWithContext(ctx, bucketName)
if err != nil {
return nil, probe.NewError(err)
}
return tags.ToMap(), nil
return tags, nil
}
tags, err := c.api.GetObjectTagging(ctx, bucketName, objectName, minio.GetObjectTaggingOptions{})
s, err := c.api.GetObjectTaggingWithContext(ctx, bucketName, objectName)
if err != nil {
return nil, probe.NewError(err)
}
return tags.ToMap(), nil
tags, err := tags.ParseObjectXML(strings.NewReader(s))
if err != nil {
return nil, probe.NewError(err)
}
return tags, nil
}
// SetTags - Set tags of bucket or object.
@@ -2220,9 +2231,9 @@ func (c *S3Client) SetTags(ctx context.Context, tagString string) *probe.Error {
}
if objectName == "" {
err = c.api.SetBucketTagging(ctx, bucketName, tags)
err = c.api.SetBucketTaggingWithContext(ctx, bucketName, tags)
} else {
err = c.api.PutObjectTagging(ctx, bucketName, objectName, tags, minio.PutObjectTaggingOptions{})
err = c.api.PutObjectTaggingWithContext(ctx, bucketName, objectName, tags.ToMap())
}
if err != nil {
@@ -2241,9 +2252,9 @@ func (c *S3Client) DeleteTags(ctx context.Context) *probe.Error {
var err error
if objectName == "" {
err = c.api.RemoveBucketTagging(ctx, bucketName)
err = c.api.DeleteBucketTaggingWithContext(ctx, bucketName)
} else {
err = c.api.RemoveObjectTagging(ctx, bucketName, objectName, minio.RemoveObjectTaggingOptions{})
err = c.api.RemoveObjectTaggingWithContext(ctx, bucketName, objectName)
}
if err != nil {
@@ -2254,28 +2265,42 @@ func (c *S3Client) DeleteTags(ctx context.Context) *probe.Error {
}
// GetLifecycle - Get current lifecycle configuration.
func (c *S3Client) GetLifecycle(ctx context.Context) (*lifecycle.Configuration, *probe.Error) {
func (c *S3Client) GetLifecycle(ctx context.Context) (ilm.LifecycleConfiguration, *probe.Error) {
bucket, _ := c.url2BucketAndObject()
if bucket == "" {
return nil, probe.NewError(BucketNameEmpty{})
return ilm.LifecycleConfiguration{}, probe.NewError(BucketNameEmpty{})
}
config, e := c.api.GetBucketLifecycle(ctx, bucket)
lifecycleXML, e := c.api.GetBucketLifecycleWithContext(ctx, bucket)
if e != nil {
return nil, probe.NewError(e)
return ilm.LifecycleConfiguration{}, probe.NewError(e)
}
return config, nil
lfcCfg := ilm.LifecycleConfiguration{}
if e = xml.Unmarshal([]byte(lifecycleXML), &lfcCfg); e != nil && e != io.EOF {
return lfcCfg, probe.NewError(e)
}
return lfcCfg, nil
}
// SetLifecycle - Set lifecycle configuration on a bucket
func (c *S3Client) SetLifecycle(ctx context.Context, config *lifecycle.Configuration) *probe.Error {
func (c *S3Client) SetLifecycle(ctx context.Context, ilmCfg ilm.LifecycleConfiguration) *probe.Error {
bucket, _ := c.url2BucketAndObject()
if bucket == "" {
return probe.NewError(BucketNameEmpty{})
}
if e := c.api.SetBucketLifecycle(ctx, bucket, config); e != nil {
var lifecycleXML []byte
if len(ilmCfg.Rules) != 0 {
var e error
lifecycleXML, e = xml.Marshal(ilmCfg)
if e != nil {
return probe.NewError(e)
}
}
if e := c.api.SetBucketLifecycleWithContext(ctx, bucket, string(lifecycleXML)); e != nil {
return probe.NewError(e)
}
+1 -1
View File
@@ -25,7 +25,7 @@ import (
"net/http/httptest"
"strconv"
minio "github.com/minio/minio-go/v7"
minio "github.com/minio/minio-go/v6"
. "gopkg.in/check.v1"
)
+8 -7
View File
@@ -22,10 +22,11 @@ import (
"os"
"time"
"github.com/minio/mc/cmd/ilm"
"github.com/minio/mc/pkg/probe"
minio "github.com/minio/minio-go/v7"
"github.com/minio/minio-go/v7/pkg/encrypt"
"github.com/minio/minio-go/v7/pkg/lifecycle"
minio "github.com/minio/minio-go/v6"
"github.com/minio/minio-go/v6/pkg/encrypt"
"github.com/minio/minio-go/v6/pkg/tags"
)
// DirOpt - list directory option.
@@ -76,7 +77,7 @@ type Client interface {
// I/O operations with expiration
ShareDownload(ctx context.Context, expires time.Duration) (string, *probe.Error)
ShareUpload(context.Context, bool, time.Duration, string) (string, map[string]string, *probe.Error)
ShareUpload(bool, time.Duration, string) (string, map[string]string, *probe.Error)
// Watch events
Watch(ctx context.Context, options WatchOptions) (*WatchObject, *probe.Error)
@@ -89,13 +90,13 @@ type Client interface {
AddUserAgent(app, version string)
// Tagging operations
GetTags(ctx context.Context) (map[string]string, *probe.Error)
GetTags(ctx context.Context) (*tags.Tags, *probe.Error)
SetTags(ctx context.Context, tags string) *probe.Error
DeleteTags(ctx context.Context) *probe.Error
// Lifecycle operations
GetLifecycle(ctx context.Context) (*lifecycle.Configuration, *probe.Error)
SetLifecycle(ctx context.Context, config *lifecycle.Configuration) *probe.Error
GetLifecycle(ctx context.Context) (ilm.LifecycleConfiguration, *probe.Error)
SetLifecycle(ctx context.Context, lfcCfg ilm.LifecycleConfiguration) *probe.Error
}
// ClientContent - Content container for content metadata
+15 -20
View File
@@ -33,8 +33,8 @@ import (
"github.com/minio/cli"
"github.com/minio/mc/pkg/probe"
minio "github.com/minio/minio-go/v7"
"github.com/minio/minio-go/v7/pkg/encrypt"
minio "github.com/minio/minio-go/v6"
"github.com/minio/minio-go/v6/pkg/encrypt"
)
// decode if the key is encoded key and returns the key
@@ -334,7 +334,7 @@ func putTargetStreamWithURL(urlStr string, reader io.Reader, size int64, sse enc
}
// copySourceToTargetURL copies to targetURL from source.
func copySourceToTargetURL(ctx context.Context, alias, urlStr, source, mode, until, legalHold string, size int64, progress io.Reader, srcSSE, tgtSSE encrypt.ServerSide, metadata map[string]string, disableMultipart, preserve bool) *probe.Error {
func copySourceToTargetURL(ctx context.Context, alias, urlStr, source, mode, until, legalHold string, size int64, progress io.Reader, srcSSE, tgtSSE encrypt.ServerSide, metadata map[string]string, disableMultipart bool) *probe.Error {
targetClnt, err := newClientFromAlias(alias, urlStr)
if err != nil {
@@ -344,7 +344,7 @@ func copySourceToTargetURL(ctx context.Context, alias, urlStr, source, mode, unt
metadata[AmzObjectLockMode] = mode
metadata[AmzObjectLockRetainUntilDate] = until
metadata[AmzObjectLockLegalHold] = legalHold
err = targetClnt.Copy(ctx, source, size, progress, srcSSE, tgtSSE, metadata, disableMultipart, preserve)
err = targetClnt.Copy(ctx, source, size, progress, srcSSE, tgtSSE, metadata, disableMultipart, false)
if err != nil {
return err.Trace(alias, urlStr)
@@ -369,14 +369,13 @@ func filterMetadata(metadata map[string]string) map[string]string {
// getAllMetadata - returns a map of user defined function
// by combining the usermetadata of object and values passed by attr keyword
func getAllMetadata(ctx context.Context, sourceAlias, sourceURLStr string, srcSSE encrypt.ServerSide, urls URLs) (map[string]string, *probe.Error) {
func getAllMetadata(ctx context.Context, sourceAlias, sourceURLStr string, srcSSE encrypt.ServerSide, urls URLs, preserve bool) (map[string]string, *probe.Error) {
metadata := make(map[string]string)
sourceClnt, err := newClientFromAlias(sourceAlias, sourceURLStr)
if err != nil {
return nil, err.Trace(sourceAlias, sourceURLStr)
}
st, err := sourceClnt.Stat(ctx, false, true, srcSSE)
st, err := sourceClnt.Stat(ctx, false, preserve, srcSSE)
if err != nil {
return nil, err.Trace(sourceAlias, sourceURLStr)
}
@@ -454,15 +453,13 @@ func uploadSourceToTargetURL(ctx context.Context, urls URLs, progress io.Reader,
// Optimize for server side copy if the host is same.
if sourceAlias == targetAlias {
// preserve new metadata and save existing ones.
if preserve {
currentMetadata, err := getAllMetadata(ctx, sourceAlias, sourceURL.String(), srcSSE, urls)
// If no metadata populated already by the caller
// just do a Stat() to obtain the metadata.
if len(metadata) == 0 && preserve {
metadata, err = getAllMetadata(ctx, sourceAlias, sourceURL.String(), srcSSE, urls, preserve)
if err != nil {
return urls.WithError(err.Trace(sourceURL.String()))
}
for k, v := range currentMetadata {
metadata[k] = v
}
}
// Get metadata from target content as well
@@ -482,18 +479,16 @@ func uploadSourceToTargetURL(ctx context.Context, urls URLs, progress io.Reader,
}
err = copySourceToTargetURL(ctx, targetAlias, targetURL.String(), sourcePath, mode, until,
legalHold, length, progress, srcSSE, tgtSSE, filterMetadata(metadata), urls.DisableMultipart, preserve)
legalHold, length, progress, srcSSE, tgtSSE, filterMetadata(metadata), urls.DisableMultipart)
} else {
if urls.SourceContent.RetentionEnabled {
// preserve new metadata and save existing ones.
if preserve {
currentMetadata, err := getAllMetadata(ctx, sourceAlias, sourceURL.String(), srcSSE, urls)
// If no metadata populated already by the caller
// just do a Stat() to obtain the metadata.
if len(metadata) == 0 && preserve {
metadata, err = getAllMetadata(ctx, sourceAlias, sourceURL.String(), srcSSE, urls, preserve)
if err != nil {
return urls.WithError(err.Trace(sourceURL.String()))
}
for k, v := range currentMetadata {
metadata[k] = v
}
}
// Get metadata from target content as well
+2 -2
View File
@@ -27,7 +27,7 @@ import (
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio-go/v7"
"github.com/minio/minio-go/v6"
"github.com/minio/minio/pkg/console"
"golang.org/x/crypto/ssh/terminal"
)
@@ -50,7 +50,7 @@ var configHostAddCmd = cli.Command{
ShortName: "a",
Usage: "add a new host to configuration file",
Action: mainConfigHostAdd,
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Flags: append(hostAddFlags, globalFlags...),
HideHelpCommand: true,
CustomHelpTemplate: `NAME:
+1 -1
View File
@@ -30,7 +30,7 @@ var configHostListCmd = cli.Command{
ShortName: "ls",
Usage: "list hosts in configuration file",
Action: mainConfigHostList,
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Flags: globalFlags,
HideHelpCommand: true,
CustomHelpTemplate: `NAME:
+1 -1
View File
@@ -27,7 +27,7 @@ var configHostRemoveCmd = cli.Command{
ShortName: "rm",
Usage: "remove a host from configuration file",
Action: mainConfigHostRemove,
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Flags: globalFlags,
HideHelpCommand: true,
CustomHelpTemplate: `NAME:
-1
View File
@@ -27,7 +27,6 @@ var configHostCmd = cli.Command{
Name: "host",
Usage: "add, remove and list hosts in configuration file",
Action: mainConfigHost,
Before: setGlobalsFromContext,
Flags: globalFlags,
Subcommands: []cli.Command{
configHostAddCmd,
-1
View File
@@ -37,7 +37,6 @@ var configCmd = cli.Command{
Name: "config",
Usage: "configure MinIO client",
Action: mainConfig,
Before: setGlobalsFromContext,
HideHelpCommand: true,
Flags: append(configFlags, globalFlags...),
Subcommands: []cli.Command{
+10 -106
View File
@@ -104,7 +104,7 @@ var cpCmd = cli.Command{
Name: "cp",
Usage: "copy objects",
Action: mainCopy,
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Flags: append(append(cpFlags, ioFlags...), globalFlags...),
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
@@ -492,16 +492,14 @@ func doCopySession(ctx context.Context, cancelCopy context.CancelFunc, cli *cli.
cpURLs.TargetContent.LegalHoldEnabled = true
}
}
preserve := cli.Bool("preserve")
if cli.String("attr") != "" {
preserve = true
userMetaMap, _ := getMetaDataEntry(cli.String("attr"))
for metadataKey, metaDataVal := range userMetaMap {
cpURLs.TargetContent.UserMetadata[metadataKey] = metaDataVal
for metaDataKey, metaDataVal := range userMetaMap {
cpURLs.TargetContent.UserMetadata[metaDataKey] = metaDataVal
}
}
preserve := cli.Bool("preserve")
cpURLs.MD5 = cli.Bool("md5")
cpURLs.DisableMultipart = cli.Bool("disable-multipart")
@@ -606,108 +604,14 @@ loop:
// validate the passed metadataString and populate the map
func getMetaDataEntry(metadataString string) (map[string]string, *probe.Error) {
metaDataMap := make(map[string]string)
r := strings.NewReader(metadataString)
type pToken int
const (
KEY pToken = iota
VALUE
)
type pState int
const (
NORMAL pState = iota
QSTRING
DQSTRING
)
var key, value strings.Builder
writeRune := func(ch rune, pt pToken) {
if pt == KEY {
key.WriteRune(ch)
} else if pt == VALUE {
value.WriteRune(ch)
} else {
panic("Invalid parser token type")
for _, metaData := range strings.Split(metadataString, ";") {
metaDataEntry := strings.SplitN(metaData, "=", 2)
if len(metaDataEntry) != 2 {
return nil, probe.NewError(ErrInvalidMetadata)
}
metaDataMap[http.CanonicalHeaderKey(metaDataEntry[0])] = metaDataEntry[1]
}
ps := NORMAL
pt := KEY
p := 0
for ; ; p++ {
ch, _, err := r.ReadRune()
if err != nil {
//eof
if ps == QSTRING || ps == DQSTRING || pt == KEY {
return nil, probe.NewError(ErrInvalidMetadata)
}
metaDataMap[http.CanonicalHeaderKey(key.String())] = value.String()
return metaDataMap, nil
}
if ch == '"' {
if ps == DQSTRING {
ps = NORMAL
} else if ps == QSTRING {
writeRune(ch, pt)
} else if ps == NORMAL {
ps = DQSTRING
} else {
break
}
continue
}
if ch == '\'' {
if ps == QSTRING {
ps = NORMAL
} else if ps == DQSTRING {
writeRune(ch, pt)
} else if ps == NORMAL {
ps = QSTRING
} else {
break
}
continue
}
if ch == '=' {
if ps == QSTRING || ps == DQSTRING {
writeRune(ch, pt)
} else if pt == KEY {
pt = VALUE
} else if pt == VALUE {
writeRune(ch, pt)
} else {
break
}
continue
}
if ch == ';' {
if ps == QSTRING || ps == DQSTRING {
writeRune(ch, pt)
} else if pt == KEY {
return nil, probe.NewError(ErrInvalidMetadata)
} else if pt == VALUE {
metaDataMap[http.CanonicalHeaderKey(key.String())] = value.String()
key.Reset()
value.Reset()
pt = KEY
} else {
break
}
continue
}
writeRune(ch, pt)
}
fatalErr := fmt.Sprintf("Invalid parser state at index: %d", p)
panic(fatalErr)
return metaDataMap, nil
}
// mainCopy is the entry point for cp command.
-12
View File
@@ -38,18 +38,6 @@ func TestParseMetaData(t *testing.T) {
{"key1:value1;key2:value2", nil, ErrInvalidMetadata, false},
// using no delimiter
{"key1:value1:key2:value2", nil, ErrInvalidMetadata, false},
//success: use value in quotes
{"Content-Disposition='form-data; name=\"description\"'", map[string]string{"Content-Disposition": "form-data; name=\"description\""}, nil, true},
//success: use value in double quotes
{"Content-Disposition=\"form-data; name='description'\"", map[string]string{"Content-Disposition": "form-data; name='description'"}, nil, true},
//fail: unterminated quote
{"Content-Disposition='form-data; name=\"description\"", nil, ErrInvalidMetadata, false},
//fail: unterminated double quote
{"Content-Disposition=\"form-data; name='description'", nil, ErrInvalidMetadata, false},
//success: use value and key in quotes
{"\"Content-Disposition\"='form-data; name=\"description\"'", map[string]string{"Content-Disposition": "form-data; name=\"description\""}, nil, true},
//success: use value and key in quotes
{"\"Content=Disposition;Other key part=this is also key data\"='form-data; name=\"description\"'", map[string]string{"Content=Disposition;Other key part=this is also key data": "form-data; name=\"description\""}, nil, true},
}
for idx, testCase := range metaDataCases {
+1 -1
View File
@@ -38,7 +38,7 @@ var diffCmd = cli.Command{
Name: "diff",
Usage: "list differences in object name, size, and date between two buckets",
Action: mainDiff,
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Flags: append(diffFlags, globalFlags...),
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
+1 -1
View File
@@ -25,7 +25,7 @@ import (
// golang does not support flat keys for path matching, find does
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio-go/v7"
"github.com/minio/minio-go/v6"
"golang.org/x/text/unicode/norm"
)
+1 -1
View File
@@ -48,7 +48,7 @@ var duCmd = cli.Command{
Name: "du",
Usage: "summarize disk usage recursively",
Action: mainDu,
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Flags: append(append(duFlags, ioFlags...), globalFlags...),
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
+1 -1
View File
@@ -53,7 +53,7 @@ var eventAddCmd = cli.Command{
Name: "add",
Usage: "add a new bucket notification",
Action: mainEventAdd,
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Flags: append(eventAddFlags, globalFlags...),
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
+1 -1
View File
@@ -35,7 +35,7 @@ var eventListCmd = cli.Command{
Name: "list",
Usage: "list bucket notifications",
Action: mainEventList,
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Flags: append(eventListFlags, globalFlags...),
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
-1
View File
@@ -27,7 +27,6 @@ var eventCmd = cli.Command{
Usage: "configure object notifications",
HideHelpCommand: true,
Action: mainEvent,
Before: setGlobalsFromContext,
Flags: append(eventFlags, globalFlags...),
Subcommands: []cli.Command{
eventAddCmd,
+6 -1
View File
@@ -20,6 +20,8 @@ import (
"context"
"errors"
"github.com/minio/minio-go/v6"
"github.com/fatih/color"
"github.com/minio/cli"
json "github.com/minio/mc/pkg/colorjson"
@@ -52,7 +54,7 @@ var eventRemoveCmd = cli.Command{
Name: "remove",
Usage: "remove a bucket notification; '--force' removes all bucket notifications",
Action: mainEventRemove,
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Flags: append(eventRemoveFlags, globalFlags...),
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
@@ -134,6 +136,9 @@ func mainEventRemove(cliCtx *cli.Context) error {
err = s3Client.RemoveNotificationConfig(ctx, arn, event, prefix, suffix)
if err != nil {
if err.Cause == minio.ErrNoNotificationConfigMatch {
fatalIf(err, "Remove event failed.")
}
fatalIf(err, "Cannot disable notification on the specified bucket.")
}
+1 -1
View File
@@ -85,7 +85,7 @@ var findCmd = cli.Command{
Name: "find",
Usage: "search for objects",
Action: mainFind,
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Flags: append(findFlags, globalFlags...),
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
+5 -5
View File
@@ -83,11 +83,11 @@ func setGlobals(quiet, debug, json, noColor, insecure bool) {
// Set global states. NOTE: It is deliberately kept monolithic to ensure we dont miss out any flags.
func setGlobalsFromContext(ctx *cli.Context) error {
quiet := ctx.IsSet("quiet") || ctx.GlobalIsSet("quiet")
debug := ctx.IsSet("debug") || ctx.GlobalIsSet("debug")
json := ctx.IsSet("json") || ctx.GlobalIsSet("json")
noColor := ctx.IsSet("no-color") || ctx.GlobalIsSet("no-color")
insecure := ctx.IsSet("insecure") || ctx.GlobalIsSet("insecure")
quiet := ctx.IsSet("quiet")
debug := ctx.IsSet("debug")
json := ctx.IsSet("json")
noColor := ctx.IsSet("no-color")
insecure := ctx.IsSet("insecure")
setGlobals(quiet, debug, json, noColor, insecure)
return nil
}
+1 -1
View File
@@ -46,7 +46,7 @@ var headCmd = cli.Command{
Name: "head",
Usage: "display first 'n' lines of an object",
Action: mainHead,
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Flags: append(append(headFlags, ioFlags...), globalFlags...),
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
+1 -1
View File
@@ -30,7 +30,7 @@ var ilmAddCmd = cli.Command{
Name: "add",
Usage: "add a lifecycle configuration rule to existing (if any) rule(s) on a bucket",
Action: mainILMAdd,
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Flags: append(ilmAddFlags, globalFlags...),
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
+9 -9
View File
@@ -21,16 +21,16 @@ import (
"errors"
"github.com/minio/cli"
"github.com/minio/mc/cmd/ilm"
json "github.com/minio/mc/pkg/colorjson"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio-go/v7/pkg/lifecycle"
)
var ilmExportCmd = cli.Command{
Name: "export",
Usage: "export lifecycle configuration in JSON format",
Action: mainILMExport,
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
@@ -51,13 +51,13 @@ EXAMPLES:
}
type ilmExportMessage struct {
Status string `json:"status"`
Target string `json:"target"`
Config *lifecycle.Configuration `json:"config"`
Status string `json:"status"`
Target string `json:"target"`
ILMConfig ilm.LifecycleConfiguration `json:"ilmConfig"`
}
func (i ilmExportMessage) String() string {
msgBytes, e := json.MarshalIndent(i.Config, "", " ")
msgBytes, e := json.MarshalIndent(i.ILMConfig, "", " ")
fatalIf(probe.NewError(e), "Unable to export ILM configuration")
return string(msgBytes)
@@ -98,9 +98,9 @@ func mainILMExport(cliCtx *cli.Context) error {
}
printMsg(ilmExportMessage{
Status: "success",
Target: urlStr,
Config: ilmCfg,
Status: "success",
Target: urlStr,
ILMConfig: ilmCfg,
})
return nil
+7 -9
View File
@@ -21,9 +21,9 @@ import (
"os"
"github.com/minio/cli"
"github.com/minio/mc/cmd/ilm"
json "github.com/minio/mc/pkg/colorjson"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio-go/v7/pkg/lifecycle"
"github.com/minio/minio/pkg/console"
)
@@ -31,7 +31,7 @@ var ilmImportCmd = cli.Command{
Name: "import",
Usage: "import lifecycle configuration in JSON format",
Action: mainILMImport,
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
@@ -67,17 +67,15 @@ func (i ilmImportMessage) JSON() string {
}
// readILMConfig read from stdin, returns XML.
func readILMConfig() (*lifecycle.Configuration, *probe.Error) {
func readILMConfig() (ilm.LifecycleConfiguration, *probe.Error) {
// User is expected to enter the lifecycleConfiguration instance contents in JSON format
var cfg = lifecycle.NewConfiguration()
var ilmCfg ilm.LifecycleConfiguration
// Consume json from STDIN
dec := json.NewDecoder(os.Stdin)
if e := dec.Decode(cfg); e != nil {
return cfg, probe.NewError(e)
if e := dec.Decode(&ilmCfg); e != nil {
return ilmCfg, probe.NewError(e)
}
return cfg, nil
return ilmCfg, nil
}
// checkILMImportSyntax - validate arguments passed by user
+10 -11
View File
@@ -27,7 +27,6 @@ import (
"github.com/minio/mc/cmd/ilm"
json "github.com/minio/mc/pkg/colorjson"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio-go/v7/pkg/lifecycle"
"github.com/minio/minio/pkg/console"
)
@@ -50,7 +49,7 @@ var ilmListCmd = cli.Command{
Name: "list",
Usage: "pretty print bucket lifecycle configuration",
Action: mainILMList,
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Flags: append(ilmListFlags, globalFlags...),
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
@@ -83,10 +82,10 @@ EXAMPLES:
}
type ilmListMessage struct {
Status string `json:"status"`
Target string `json:"target"`
Context *cli.Context `json:"-"`
Config *lifecycle.Configuration `json:"config"`
Status string `json:"status"`
Target string `json:"target"`
Context *cli.Context `json:"-"`
ILMConfig ilm.LifecycleConfiguration `json:"ilmConfig"`
}
func (i ilmListMessage) String() string {
@@ -103,7 +102,7 @@ func (i ilmListMessage) String() string {
var tagRows map[string][]string
var tbl PrettyTable
ilm.PopulateILMDataForDisplay(i.Config, &hdrLabelIndexMap, &alignedHdrLabels,
ilm.PopulateILMDataForDisplay(i.ILMConfig, &hdrLabelIndexMap, &alignedHdrLabels,
&cellDataNoTags, &cellDataWithTags, &tagRows,
showAll, showMinimum, showExpiry, showTransition)
@@ -277,10 +276,10 @@ func mainILMList(cliCtx *cli.Context) error {
}
printMsg(ilmListMessage{
Status: "success",
Target: urlStr,
Context: cliCtx,
Config: ilmCfg,
Status: "success",
Target: urlStr,
Context: cliCtx,
ILMConfig: ilmCfg,
})
return nil
-1
View File
@@ -26,7 +26,6 @@ var ilmCmd = cli.Command{
Name: "ilm",
Usage: "configure bucket lifecycle",
Action: mainILM,
Before: setGlobalsFromContext,
Flags: globalFlags,
HideHelpCommand: true,
Subcommands: []cli.Command{
+3 -2
View File
@@ -45,7 +45,7 @@ var ilmRemoveCmd = cli.Command{
Name: "remove",
Usage: "remove (if any) existing lifecycle configuration rule with the id",
Action: mainILMRemove,
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Flags: append(ilmRemoveFlags, globalFlags...),
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
@@ -56,6 +56,7 @@ USAGE:
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
DESCRIPTION:
Remove a lifecycle configuration rule for the bucket by ID, optionally you can remove
all the lifecycle rules on a bucket with '--all --force' option.
@@ -64,7 +65,7 @@ EXAMPLES:
1. Remove the lifecycle management configuration rule given by ID "Documents" for testbucket on alias 'myminio'. ID is case sensitive.
{{.Prompt}} {{.HelpName}} --id "Documents" myminio/testbucket
2. Remove ALL the lifecycle management configuration rules for testbucket on alias 'myminio'.
2. Remove ALL the lifecycle management configuration rules for testbucket on alias 'myminio'.
Because the result is complete removal, the use of --force flag is enforced.
{{.Prompt}} {{.HelpName}} --all --force myminio/testbucket
`,
+105
View File
@@ -0,0 +1,105 @@
/*
* MinIO Client (C) 2020 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Package ilm contains all the ilm related functionality. TO BE ACCESSED VIA GET FUNCTIONS or Operation-related Global functions.
package ilm
import (
"encoding/xml"
"time"
)
// AbortIncompleteMultipartUpload structure
type AbortIncompleteMultipartUpload struct {
XMLName xml.Name `xml:"AbortIncompleteMultipartUpload,omitempty" json:"-"`
DaysAfterInitiation int64 `xml:"DaysAfterInitiation,omitempty" json:"DaysAfterInitiation,omitempty"`
}
// NoncurrentVersionTransition structure
type NoncurrentVersionTransition struct {
XMLName xml.Name `xml:"NoncurrentVersionTransition,omitempty" json:"-"`
StorageClass string `xml:"StorageClass,omitempty" json:"StorageClass,omitempty"`
TransitionInDays int `xml:"TransitionInDays,omitempty" json:"TransitionInDays,omitempty"`
}
// LifecycleTag structure key/value pair representing an object tag to apply lifecycle configuration
type LifecycleTag struct {
XMLName xml.Name `xml:"Tag,omitempty" json:"-"`
Key string `xml:"Key,omitempty" json:"Key,omitempty"`
Value string `xml:"Value,omitempty" json:"Value,omitempty"`
}
// LifecycleTransition structure - transition details of lifecycle configuration
type LifecycleTransition struct {
XMLName xml.Name `xml:"Transition" json:"-"`
TransitionDate *time.Time `xml:"Date,omitempty" json:"Date,omitempty"`
StorageClass string `xml:"StorageClass,omitempty" json:"StorageClass,omitempty"`
TransitionInDays int `xml:"Days,omitempty" json:"Days,omitempty"`
}
// IsSet is transition set
func (t LifecycleTransition) IsSet() bool {
return t.TransitionDate != nil && !t.TransitionDate.IsZero() || t.TransitionInDays > 0
}
// LifecycleAndOperator And Rule for LifecycleTag, to be used in LifecycleRuleFilter
type LifecycleAndOperator struct {
XMLName xml.Name `xml:"And,omitempty" json:"-"`
Prefix string `xml:"Prefix,omitempty" json:"Prefix,omitempty"`
Tags []LifecycleTag `xml:"Tag,omitempty" json:"Tags,omitempty"`
}
// LifecycleRuleFilter will be used in selecting rule(s) for lifecycle configuration
type LifecycleRuleFilter struct {
XMLName xml.Name `xml:"Filter" json:"-"`
And *LifecycleAndOperator `xml:"And,omitempty" json:"And,omitempty"`
Prefix string `xml:"Prefix,omitempty" json:"Prefix,omitempty"`
Tag *LifecycleTag `xml:"Tag,omitempty" json:"-"`
}
// LifecycleExpiration structure - expiration details of lifecycle configuration
type LifecycleExpiration struct {
XMLName xml.Name `xml:"Expiration,omitempty" json:"-"`
ExpirationDate *time.Time `xml:"Date,omitempty" json:"Date,omitempty"`
ExpirationInDays int `xml:"Days,omitempty" json:"Days,omitempty"`
}
// IsSet - is LifecycleExpiration set?
func (e LifecycleExpiration) IsSet() bool {
return e.ExpirationDate != nil && !e.ExpirationDate.IsZero() || e.ExpirationInDays > 0
}
// LifecycleRule represents a single rule in lifecycle configuration
type LifecycleRule struct {
XMLName xml.Name `xml:"Rule,omitempty" json:"-"`
AbortIncompleteMultipartUpload *AbortIncompleteMultipartUpload `xml:"AbortIncompleteMultipartUpload,omitempty" json:"AbortIncompleteMultipartUpload,omitempty"`
Expiration *LifecycleExpiration `xml:"Expiration,omitempty" json:"Expiration,omitempty"`
ID string `xml:"ID" json:"ID"`
RuleFilter *LifecycleRuleFilter `xml:"Filter,omitempty" json:"Filter,omitempty"`
NoncurrentVersionTransition *NoncurrentVersionTransition `xml:"NoncurrentVersionTransition,omitempty" json:"NoncurrentVersionTransition,omitempty"`
NoncurrentVersionTransitions []NoncurrentVersionTransition `xml:"NoncurrentVersionTransitions,omitempty" json:"NoncurrentVersionTransitions,omitempty"`
Prefix string `xml:"Prefix,omitempty" json:"Prefix,omitempty"`
Status string `xml:"Status" json:"Status"`
Transition *LifecycleTransition `xml:"Transition,omitempty" json:"Transition,omitempty"`
Transitions []LifecycleTransition `xml:"Transitions,omitempty" json:"Transitions,omitempty"`
TagFilters []LifecycleTag `xml:"Tag,omitempty" json:"Tags,omitempty"`
}
// LifecycleConfiguration is a collection of LifecycleRule objects.
type LifecycleConfiguration struct {
XMLName xml.Name `xml:"LifecycleConfiguration,omitempty" json:"-"`
Rules []LifecycleRule `xml:"Rule"`
}
+29 -24
View File
@@ -23,7 +23,6 @@ import (
"github.com/minio/cli"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio-go/v7/pkg/lifecycle"
)
const defaultILMDateFormat string = "2006-01-02"
@@ -74,10 +73,7 @@ func getRightAligned(label string, maxLen int) string {
}
// RemoveILMRule - Remove the ILM rule (with ilmID) from the configuration in XML that is provided.
func RemoveILMRule(lfcCfg *lifecycle.Configuration, ilmID string) (*lifecycle.Configuration, *probe.Error) {
if lfcCfg == nil {
return lfcCfg, probe.NewError(fmt.Errorf("lifecycle configuration not set"))
}
func RemoveILMRule(lfcCfg LifecycleConfiguration, ilmID string) (LifecycleConfiguration, *probe.Error) {
if len(lfcCfg.Rules) == 0 {
return lfcCfg, probe.NewError(fmt.Errorf("lifecycle configuration not set"))
}
@@ -109,60 +105,69 @@ type lifecycleOptions struct {
StorageClass string
}
func (opts lifecycleOptions) ToConfig(config *lifecycle.Configuration) (*lifecycle.Configuration, *probe.Error) {
expiry, err := parseExpiry(opts.ExpiryDate, opts.ExpiryDays)
func (opts lifecycleOptions) ToConfig(lfcCfg LifecycleConfiguration) (LifecycleConfiguration, *probe.Error) {
ilmExpiry, err := parseExpiry(opts.ExpiryDate, opts.ExpiryDays)
if err != nil {
return nil, err.Trace(opts.ExpiryDate, opts.ExpiryDays)
return lfcCfg, err.Trace(opts.ExpiryDate, opts.ExpiryDays)
}
transition, err := parseTransition(opts.StorageClass, opts.TransitionDate, opts.TransitionDays)
ilmTransition, err := parseTransition(opts.StorageClass, opts.TransitionDate, opts.TransitionDays)
if err != nil {
return nil, err.Trace(opts.StorageClass, opts.TransitionDate, opts.TransitionDays)
return lfcCfg, err.Trace(opts.StorageClass, opts.TransitionDate, opts.TransitionDays)
}
andVal := lifecycle.And{
andVal := LifecycleAndOperator{
Tags: extractILMTags(opts.Tags),
}
filter := lifecycle.Filter{Prefix: opts.Prefix}
filter := LifecycleRuleFilter{Prefix: opts.Prefix}
if len(andVal.Tags) > 0 {
filter.And = andVal
filter.And = &andVal
filter.And.Prefix = opts.Prefix
filter.Prefix = ""
}
newRule := lifecycle.Rule{
var expP *LifecycleExpiration
var transP *LifecycleTransition
if ilmTransition.IsSet() {
transP = &ilmTransition
}
if ilmExpiry.IsSet() {
expP = &ilmExpiry
}
newRule := LifecycleRule{
ID: opts.ID,
RuleFilter: filter,
RuleFilter: &filter,
Status: func() string {
if opts.Status {
return "Enabled"
}
return "Disabled"
}(),
Expiration: expiry,
Transition: transition,
Expiration: expP,
Transition: transP,
}
if err := validateILMRule(newRule); err != nil {
return nil, err.Trace(opts.ID)
return lfcCfg, err.Trace(opts.ID)
}
ruleFound := false
for i, rule := range config.Rules {
for i, rule := range lfcCfg.Rules {
if rule.ID != newRule.ID {
continue
}
config.Rules[i] = newRule
lfcCfg.Rules[i] = newRule
ruleFound = true
break
}
if !ruleFound {
config.Rules = append(config.Rules, newRule)
lfcCfg.Rules = append(lfcCfg.Rules, newRule)
}
return config, nil
return lfcCfg, nil
}
func getLifecycleOptions(ctx *cli.Context) lifecycleOptions {
@@ -181,7 +186,7 @@ func getLifecycleOptions(ctx *cli.Context) lifecycleOptions {
// ApplyNewILMConfig apply new lifecycle rules to existing lifecycle configuration, this
// function returns modified/overwritten rules if any.
func ApplyNewILMConfig(ctx *cli.Context, config *lifecycle.Configuration) (*lifecycle.Configuration, *probe.Error) {
func ApplyNewILMConfig(ctx *cli.Context, lfcCfg LifecycleConfiguration) (LifecycleConfiguration, *probe.Error) {
opts := getLifecycleOptions(ctx)
return opts.ToConfig(config)
return opts.ToConfig(lfcCfg)
}
+46 -46
View File
@@ -23,18 +23,17 @@ import (
"time"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio-go/v7/pkg/lifecycle"
)
// Extracts the tags provided by user. The tagfilter array will be put in lifecycleRule structure.
func extractILMTags(tagLabelVal string) []lifecycle.Tag {
var ilmTagKVList []lifecycle.Tag
func extractILMTags(tagLabelVal string) []LifecycleTag {
var ilmTagKVList []LifecycleTag
for _, tag := range strings.Split(tagLabelVal, tagSeperator) {
if tag == "" {
// split returns empty for empty tagLabelVal, skip it.
continue
}
lfcTag := lifecycle.Tag{}
lfcTag := LifecycleTag{}
kvs := strings.SplitN(tag, keyValSeperator, 2)
if len(kvs) == 2 {
lfcTag.Key = kvs[0]
@@ -50,40 +49,41 @@ func extractILMTags(tagLabelVal string) []lifecycle.Tag {
// Some of these rules are enforced by Amazon S3 standards.
// For example: Transition has to happen before Expiry.
// Storage class must be specified if transition date/days is provided.
func validateTranExpDate(rule lifecycle.Rule) error {
expiryDateSet := rule.Expiration.IsDateNull()
expiryDaySet := rule.Expiration.IsDaysNull()
func validateTranExpDate(rule LifecycleRule) error {
expirySet := (rule.Expiration != nil)
expiryDateSet := expirySet && rule.Expiration.ExpirationDate != nil && !rule.Expiration.ExpirationDate.IsZero()
expiryDaySet := expirySet && rule.Expiration.ExpirationInDays > 0
transitionSet := !rule.Transition.IsNull()
transitionDateSet := transitionSet && !rule.Transition.IsDateNull()
transitionDaySet := transitionSet && !rule.Transition.IsDaysNull()
transitionSet := (rule.Transition != nil)
transitionDateSet := transitionSet && (rule.Transition.TransitionDate != nil && !rule.Transition.TransitionDate.IsZero())
transitionDaySet := transitionSet && (rule.Transition.TransitionInDays > 0)
errMsg := "Error in Transition/Expiration Date/days compatibility. Transition should happen before Expiration"
if transitionDateSet && expiryDateSet {
if rule.Expiration.Date.Before(rule.Transition.Date.Time) {
if rule.Expiration.ExpirationDate.Before(*(rule.Transition.TransitionDate)) {
return errors.New(errMsg)
}
}
if transitionDaySet && expiryDaySet {
if rule.Transition.Days >= rule.Expiration.Days {
if rule.Transition.TransitionInDays >= rule.Expiration.ExpirationInDays {
return errors.New(errMsg)
}
}
return nil
}
func validateTranDays(rule lifecycle.Rule) error {
transitionSet := !rule.Transition.IsNull()
transitionDaySet := transitionSet && !rule.Transition.IsDaysNull()
if transitionDaySet && rule.Transition.Days < 30 && strings.ToLower(rule.Transition.StorageClass) == "standard_ia" {
func validateTranDays(rule LifecycleRule) error {
transitionSet := (rule.Transition != nil)
transitionDaySet := transitionSet && (rule.Transition.TransitionInDays > 0)
if transitionDaySet && rule.Transition.TransitionInDays < 30 && strings.ToLower(rule.Transition.StorageClass) == "standard_ia" {
return errors.New("Transition Date/Days are less than or equal to 30 when Storage class is STANDARD_IA")
}
return nil
}
// Amazon S3 requires a minimum of one action for a rule to be added.
func validateRuleAction(rule lifecycle.Rule) error {
expirySet := !rule.Expiration.IsNull()
transitionSet := !rule.Transition.IsNull()
func validateRuleAction(rule LifecycleRule) error {
expirySet := (rule.Expiration != nil)
transitionSet := (rule.Transition != nil)
if !expirySet && !transitionSet {
errMsg := "At least one action (Expiry or Transition) needs to be specified in a rule."
return errors.New(errMsg)
@@ -92,28 +92,28 @@ func validateRuleAction(rule lifecycle.Rule) error {
}
// Check if any date is before than cur date
func validateTranExpCurdate(rule lifecycle.Rule) error {
var e error
expirySet := !rule.Expiration.IsNull()
transitionSet := !rule.Transition.IsNull()
transitionDateSet := transitionSet && !rule.Transition.IsDateNull()
expiryDateSet := expirySet && !rule.Expiration.IsDateNull()
func validateTranExpCurdate(rule LifecycleRule) error {
var err error
expirySet := (rule.Expiration != nil)
transitionSet := (rule.Transition != nil)
transitionDateSet := transitionSet && (rule.Transition.TransitionDate != nil && !rule.Transition.TransitionDate.IsZero())
expiryDateSet := expirySet && rule.Expiration.ExpirationDate != nil && !rule.Expiration.ExpirationDate.IsZero()
currentTime := time.Now()
curTimeStr := currentTime.Format(defaultILMDateFormat)
currentTime, e = time.Parse(defaultILMDateFormat, curTimeStr)
if e != nil {
return e
currentTime, err = time.Parse(defaultILMDateFormat, curTimeStr)
if err != nil {
return err
}
if expirySet && expiryDateSet && rule.Expiration.Date.Before(currentTime) {
e = errors.New("Expiry date falls before or on today's date")
} else if transitionSet && transitionDateSet && rule.Transition.Date.Before(currentTime) {
e = errors.New("Transition date falls before or on today's date")
if expirySet && expiryDateSet && rule.Expiration.ExpirationDate.Before(currentTime) {
err = errors.New("Expiry date falls before or on today's date")
} else if transitionSet && transitionDateSet && rule.Transition.TransitionDate.Before(currentTime) {
err = errors.New("Transition date falls before or on today's date")
}
return e
return err
}
// Check S3 compatibility for the new rule and some other basic checks.
func validateILMRule(rule lifecycle.Rule) *probe.Error {
func validateILMRule(rule LifecycleRule) *probe.Error {
if e := validateRuleAction(rule); e != nil {
return probe.NewError(e)
}
@@ -130,23 +130,23 @@ func validateILMRule(rule lifecycle.Rule) *probe.Error {
}
// Returns valid lifecycleTransition to be included in lifecycleRule
func parseTransition(storageClass, transitionDateStr, transitionDayStr string) (transition lifecycle.Transition, err *probe.Error) {
func parseTransition(storageClass, transitionDateStr, transitionDayStr string) (transition LifecycleTransition, err *probe.Error) {
storageClass = strings.ToUpper(storageClass) // Just-in-case the user has entered lower case characters.
if storageClass != "" {
if transitionDateStr != "" {
transitionDate, e := time.Parse(defaultILMDateFormat, transitionDateStr)
if e != nil {
return lifecycle.Transition{}, probe.NewError(e)
return LifecycleTransition{}, probe.NewError(e)
}
transition.Date = lifecycle.ExpirationDate{Time: transitionDate}
transition.TransitionDate = &transitionDate
} else if transitionDayStr != "" {
transitionDay, e := strconv.Atoi(transitionDayStr)
if e != nil {
return lifecycle.Transition{}, probe.NewError(e)
return LifecycleTransition{}, probe.NewError(e)
}
transition.Days = lifecycle.ExpirationDays(transitionDay)
transition.TransitionInDays = transitionDay
} else {
return lifecycle.Transition{}, probe.NewError(errors.New("if storage class is set a valid transitionDate or transitionDay must be set"))
return LifecycleTransition{}, probe.NewError(errors.New("if storage class is set a valid transitionDate or transitionDay must be set"))
}
transition.StorageClass = storageClass
}
@@ -155,16 +155,16 @@ func parseTransition(storageClass, transitionDateStr, transitionDayStr string) (
}
// Returns lifecycleExpiration to be included in lifecycleRule
func parseExpiry(expiryDateStr, expiryDayStr string) (lfcExp lifecycle.Expiration, err *probe.Error) {
func parseExpiry(expiryDateStr, expiryDayStr string) (lfcExp LifecycleExpiration, err *probe.Error) {
if expiryDateStr != "" {
date, e := time.Parse(defaultILMDateFormat, expiryDateStr)
if e != nil {
return lifecycle.Expiration{}, probe.NewError(e)
return LifecycleExpiration{}, probe.NewError(e)
}
if date.IsZero() {
return lifecycle.Expiration{}, probe.NewError(errors.New("expiration date cannot be set to zero"))
return LifecycleExpiration{}, probe.NewError(errors.New("expiration date cannot be set to zero"))
}
lfcExp.Date = lifecycle.ExpirationDate{Time: date}
lfcExp.ExpirationDate = &date
}
if expiryDayStr != "" {
@@ -173,9 +173,9 @@ func parseExpiry(expiryDateStr, expiryDayStr string) (lfcExp lifecycle.Expiratio
return lfcExp, probe.NewError(e)
}
if days == 0 {
return lifecycle.Expiration{}, probe.NewError(errors.New("expiration days cannot be set to zero"))
return LifecycleExpiration{}, probe.NewError(errors.New("expiration days cannot be set to zero"))
}
lfcExp.Days = lifecycle.ExpirationDays(days)
lfcExp.ExpirationInDays = days
}
return lfcExp, nil
+64 -49
View File
@@ -18,8 +18,6 @@ package ilm
import (
"strconv"
"github.com/minio/minio-go/v7/pkg/lifecycle"
)
const (
@@ -102,7 +100,7 @@ type showDetails struct {
// PopulateILMDataForDisplay based on showDetails determined by user input, populate the ILM display
// table with information. Table is constructed row-by-row. Headers are first, then the rest of the rows.
func PopulateILMDataForDisplay(ilmCfg *lifecycle.Configuration, rowCheck *map[string]int, alignedHdrLabels *[]string,
func PopulateILMDataForDisplay(ilmCfg LifecycleConfiguration, rowCheck *map[string]int, alignedHdrLabels *[]string,
cellDataNoTags *[][]string, cellDataWithTags *[][]string, tagRows *map[string][]string,
showAll, showMin, showExpiry, showTransition bool) {
@@ -203,16 +201,18 @@ func checkAddTableCellRows(rowArr *[]string, rowCheck map[string]int, showOpts s
}
// The right kind of tick is returned. Cross-tick if expiry is not set.
func getExpiryTick(rule lifecycle.Rule) string {
func getExpiryTick(rule LifecycleRule) string {
expiryTick := crossTickCell
if !rule.Expiration.IsNull() {
expiryDateSet := rule.Expiration != nil && rule.Expiration.ExpirationDate != nil && !rule.Expiration.ExpirationDate.IsZero()
expirySet := rule.Expiration != nil && (expiryDateSet || rule.Expiration.ExpirationInDays > 0)
if expirySet {
expiryTick = tickCell
}
return expiryTick
}
// The right kind of tick is returned. Cross-tick if status is 'Disabled' & tick if status is 'Enabled'.
func getStatusTick(rule lifecycle.Rule) string {
func getStatusTick(rule LifecycleRule) string {
statusTick := crossTickCell
if rule.Status == statusLabelKey {
statusTick = tickCell
@@ -221,22 +221,26 @@ func getStatusTick(rule lifecycle.Rule) string {
}
// Expiry date. 'YYYY-MM-DD'. Set for 00:00:00 GMT as per the standard.
func getExpiryDateVal(rule lifecycle.Rule) string {
func getExpiryDateVal(rule LifecycleRule) string {
expiryDate := blankCell
if !rule.Expiration.IsDateNull() {
expiryDate = strconv.Itoa(rule.Expiration.Date.Day()) + " " +
rule.Expiration.Date.Month().String()[0:3] + " " +
strconv.Itoa(rule.Expiration.Date.Year())
} else if !rule.Expiration.IsDateNull() {
expiryDate = strconv.Itoa(int(rule.Expiration.Days)) + " day(s)"
expirySet := (rule.Expiration != nil)
expiryDateSet := expirySet && rule.Expiration.ExpirationDate != nil && !rule.Expiration.ExpirationDate.IsZero()
if expiryDateSet {
expiryDate = strconv.Itoa(rule.Expiration.ExpirationDate.Day()) + " " +
rule.Expiration.ExpirationDate.Month().String()[0:3] + " " +
strconv.Itoa(rule.Expiration.ExpirationDate.Year())
} else if expirySet && rule.Expiration.ExpirationInDays > 0 {
expiryDate = strconv.Itoa(rule.Expiration.ExpirationInDays) + " day(s)"
}
return expiryDate
}
// Cross-tick if Transition is not set.
func getTransitionTick(rule lifecycle.Rule) string {
transitionSet := !rule.Transition.IsNull()
transitionDateSet := transitionSet && !rule.Transition.IsDateNull()
func getTransitionTick(rule LifecycleRule) string {
transitionSet := rule.Transition != nil
transitionDateSet := transitionSet && ((rule.Transition.TransitionDate != nil &&
!rule.Transition.TransitionDate.IsZero()) ||
rule.Transition.TransitionInDays > 0)
if !transitionSet || !transitionDateSet {
return crossTickCell
}
@@ -244,25 +248,26 @@ func getTransitionTick(rule lifecycle.Rule) string {
}
// Transition date. 'YYYY-MM-DD'. Set for 00:00:00 GMT as per the standard.
func getTransitionDate(rule lifecycle.Rule) string {
func getTransitionDate(rule LifecycleRule) string {
transitionDate := blankCell
transitionSet := !rule.Transition.IsNull()
transitionDateSet := transitionSet && !rule.Transition.IsDateNull()
transitionDaySet := transitionSet && !rule.Transition.IsDaysNull()
transitionSet := (rule.Transition != nil)
transitionDateSet := transitionSet && (rule.Transition.TransitionDate != nil &&
!rule.Transition.TransitionDate.IsZero())
transitionDaySet := transitionSet && (rule.Transition.TransitionInDays > 0)
if transitionDateSet {
transitionDate = strconv.Itoa(rule.Transition.Date.Day()) + " " +
rule.Transition.Date.Month().String()[0:3] + " " +
strconv.Itoa(rule.Transition.Date.Year())
transitionDate = strconv.Itoa(rule.Transition.TransitionDate.Day()) + " " +
rule.Transition.TransitionDate.Month().String()[0:3] + " " +
strconv.Itoa(rule.Transition.TransitionDate.Year())
} else if transitionDaySet {
transitionDate = strconv.Itoa(int(rule.Transition.Days)) + " day(s)"
transitionDate = strconv.Itoa(rule.Transition.TransitionInDays) + " day(s)"
}
return transitionDate
}
// Storage class name for transition.
func getStorageClassName(rule lifecycle.Rule) string {
func getStorageClassName(rule LifecycleRule) string {
storageClass := blankCell
transitionSet := !rule.Transition.IsNull()
transitionSet := (rule.Transition != nil)
storageClassAvail := transitionSet && (rule.Transition.StorageClass != "")
if storageClassAvail {
storageClass = rule.Transition.StorageClass
@@ -271,12 +276,13 @@ func getStorageClassName(rule lifecycle.Rule) string {
}
// Array of Tag strings, each in key:value format
func getTagArr(rule lifecycle.Rule) []string {
if rule.RuleFilter.And.IsEmpty() {
return []string{}
func getTagArr(rule LifecycleRule) []string {
tagArr := rule.TagFilters
tagLth := len(rule.TagFilters)
if len(rule.TagFilters) == 0 && rule.RuleFilter != nil && rule.RuleFilter.And != nil {
tagLth = len(rule.RuleFilter.And.Tags)
tagArr = rule.RuleFilter.And.Tags
}
tagArr := rule.RuleFilter.And.Tags
tagLth := len(tagArr)
tagCellArr := make([]string, len(tagArr))
for tagIdx := 0; tagIdx < tagLth; tagIdx++ {
tagCellArr[tagIdx] = (tagArr[tagIdx].Key + ":" + tagArr[tagIdx].Value)
@@ -305,20 +311,22 @@ func checkAddTableCell(rowArr *[]string, rowCheck map[string]int, cellInfo table
}
// GetILMShowDataWithoutTags - Without tags
func getILMShowDataWithoutTags(cellInfo *[][]string, rowCheck map[string]int, info *lifecycle.Configuration, showOpts showDetails) {
func getILMShowDataWithoutTags(cellInfo *[][]string, rowCheck map[string]int, info LifecycleConfiguration, showOpts showDetails) {
*cellInfo = make([][]string, 0)
count := 0
for index := 0; index < len(info.Rules); index++ {
rule := info.Rules[index]
showExpiry := !rule.Expiration.IsNull()
transitionSet := !rule.Transition.IsNull()
showExpiry := (rule.Expiration != nil) && ((rule.Expiration.ExpirationDate != nil && !rule.Expiration.ExpirationDate.IsZero()) ||
rule.Expiration.ExpirationInDays > 0)
transitionSet := (rule.Transition != nil) && ((rule.Transition.TransitionDate != nil && !rule.Transition.TransitionDate.IsZero()) ||
rule.Transition.TransitionInDays > 0)
skipExpTran := (showOpts.expiry && !showExpiry) || (showOpts.transition && !transitionSet)
if skipExpTran {
continue
}
tagPresent := !rule.RuleFilter.And.IsEmpty()
if tagPresent {
tagPresent := (rule.RuleFilter != nil) && (rule.RuleFilter.And != nil)
if len(rule.TagFilters) > 0 || (tagPresent && len(rule.RuleFilter.And.Tags) > 0) {
continue
}
*cellInfo = append(*cellInfo, make([]string, 0))
@@ -345,14 +353,16 @@ func getILMShowDataWithoutTags(cellInfo *[][]string, rowCheck map[string]int, in
}
// GetILMShowDataWithTags Just the data with extra rows for extra tags
func getILMShowDataWithTags(cellInfo *[][]string, newRows map[string][]string, rowCheck map[string]int, info *lifecycle.Configuration, showOpts showDetails) {
func getILMShowDataWithTags(cellInfo *[][]string, newRows map[string][]string, rowCheck map[string]int, info LifecycleConfiguration, showOpts showDetails) {
*cellInfo = make([][]string, 0)
count := 0
for index := 0; index < len(info.Rules); index++ {
rule := info.Rules[index]
showExpiry := !rule.Expiration.IsNull()
transitionSet := !rule.Transition.IsNull()
showExpiry := (rule.Expiration != nil) && ((rule.Expiration.ExpirationDate != nil && !rule.Expiration.ExpirationDate.IsZero()) ||
rule.Expiration.ExpirationInDays > 0)
transitionSet := (rule.Transition != nil) && ((rule.Transition.TransitionDate != nil && !rule.Transition.TransitionDate.IsZero()) ||
rule.Transition.TransitionInDays > 0)
skipExpTran := (showOpts.expiry && !showExpiry) || (showOpts.transition && !transitionSet)
if skipExpTran {
continue
@@ -384,24 +394,26 @@ func getILMShowDataWithTags(cellInfo *[][]string, newRows map[string][]string, r
}
}
func getPrefixVal(rule lifecycle.Rule) string {
func getPrefixVal(rule LifecycleRule) string {
prefixVal := ""
switch {
case rule.Prefix != "":
prefixVal = rule.Prefix
case !rule.RuleFilter.And.IsEmpty():
case rule.RuleFilter != nil && rule.RuleFilter.And != nil && rule.RuleFilter.And.Prefix != "":
prefixVal = rule.RuleFilter.And.Prefix
case rule.RuleFilter.Prefix != "":
case rule.RuleFilter != nil && rule.RuleFilter.Prefix != "":
prefixVal = rule.RuleFilter.Prefix
}
return prefixVal
}
func showExpiryDetails(rule lifecycle.Rule, showOpts showDetails) bool {
func showExpiryDetails(rule LifecycleRule, showOpts showDetails) bool {
if showOpts.allAvailable {
return true
}
expirySet := !rule.Expiration.IsNull()
expirySet := (rule.Expiration != nil) &&
((rule.Expiration.ExpirationDate != nil && !rule.Expiration.ExpirationDate.IsZero()) ||
rule.Expiration.ExpirationInDays > 0)
return (expirySet && (showOpts.allAvailable || showOpts.expiry))
@@ -415,24 +427,27 @@ func showTransitionTick(showOpts showDetails) bool {
return (showOpts.allAvailable || showOpts.minimum)
}
func showTransitionDetails(rule lifecycle.Rule, showOpts showDetails) bool {
func showTransitionDetails(rule LifecycleRule, showOpts showDetails) bool {
if showOpts.allAvailable {
return true
}
transitionSet := !rule.Transition.IsNull()
transitionSet := (rule.Transition != nil) &&
((rule.Transition.TransitionDate != nil && !rule.Transition.TransitionDate.IsZero()) ||
rule.Transition.TransitionInDays > 0)
transitionDetailsShow := (showOpts.allAvailable || showOpts.transition)
return transitionSet && transitionDetailsShow
}
func showTags(rule lifecycle.Rule, showOpts showDetails) bool {
func showTags(rule LifecycleRule, showOpts showDetails) bool {
if showOpts.minimum {
return false
}
tagSet := showOpts.allAvailable || !rule.RuleFilter.And.IsEmpty()
tagSet := showOpts.allAvailable ||
(len(rule.TagFilters) > 0 || (rule.RuleFilter != nil && rule.RuleFilter.And != nil && (len(rule.RuleFilter.And.Tags) > 0)))
return tagSet
}
func getColumns(info *lifecycle.Configuration, rowCheck map[string]int, alignedHdrLabels *[]string, showOpts showDetails) {
func getColumns(info LifecycleConfiguration, rowCheck map[string]int, alignedHdrLabels *[]string, showOpts showDetails) {
tagIn := false // Keep tag in the end
colIdx := 0
colWidthTbl := getILMColumnWidthTable()
+2 -2
View File
@@ -25,7 +25,7 @@ import (
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/mc/pkg/probe"
minio "github.com/minio/minio-go/v7"
minio "github.com/minio/minio-go/v6"
"github.com/minio/minio/pkg/console"
)
@@ -41,7 +41,7 @@ var legalHoldCmd = cli.Command{
Name: "legalhold",
Usage: "set legal hold for object(s)",
Action: mainLegalHold,
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Flags: append(lhFlags, globalFlags...),
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
+2 -2
View File
@@ -26,7 +26,7 @@ import (
"github.com/minio/cli"
json "github.com/minio/mc/pkg/colorjson"
"github.com/minio/mc/pkg/probe"
minio "github.com/minio/minio-go/v7"
minio "github.com/minio/minio-go/v6"
"github.com/minio/minio/pkg/console"
)
@@ -43,7 +43,7 @@ var lockCmd = cli.Command{
Name: "lock",
Usage: "set and get object lock configuration",
Action: mainLock,
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Flags: append(lockFlags, globalFlags...),
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
+1 -1
View File
@@ -44,7 +44,7 @@ var lsCmd = cli.Command{
Name: "ls",
Usage: "list buckets and objects",
Action: mainList,
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Flags: append(lsFlags, globalFlags...),
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
+20 -25
View File
@@ -255,30 +255,6 @@ func installAutoCompletion() {
}
}
func registerBefore(ctx *cli.Context) error {
if ctx.IsSet("config-dir") {
// Set the config directory.
setMcConfigDir(ctx.String("config-dir"))
} else if ctx.GlobalIsSet("config-dir") {
// Set the config directory.
setMcConfigDir(ctx.GlobalString("config-dir"))
}
// Set global flags.
setGlobalsFromContext(ctx)
// Migrate any old version of config / state files to newer format.
migrate()
// Initialize default config files.
initMC()
// Check if config can be read.
checkConfig()
return nil
}
// findClosestCommands to match a given string with commands trie tree.
func findClosestCommands(command string) []string {
var closestCommands []string
@@ -318,6 +294,26 @@ func checkUpdate(ctx *cli.Context) {
}
}
// All the routines that need to be done before running any mc command
func initBeforeRunningCmd(ctx *cli.Context) error {
// Set global variables from the context
setGlobalsFromContext(ctx)
// Set the config directory.
setMcConfigDir(ctx.GlobalString("config-dir"))
// Migrate any old version of config / state files to newer format.
migrate()
// Initialize default config files.
initMC()
// Check if config can be read.
checkConfig()
return nil
}
var appCmds = []cli.Command{
lsCmd,
mbCmd,
@@ -377,7 +373,6 @@ func registerApp(name string) *cli.App {
return exitStatus(globalErrorExitStatus)
}
app.Before = registerBefore
app.ExtraInfo = func() map[string]string {
if globalDebug {
return getSystemData()
+50
View File
@@ -0,0 +1,50 @@
/*
* 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 (
"testing"
"github.com/minio/cli"
)
// This function checks that only leaf commands have Before
// function configured to avoid calling it multiple times.
func TestBeforeCommand(t *testing.T) {
var checkCmd func(string, cli.Command)
checkCmd = func(cmdPath string, c cli.Command) {
if len(c.Subcommands) != 0 {
if c.Before != nil {
t.Fatalf("Command %s does not expect to have a Before func since it is not the leaf command", cmdPath)
}
} else {
if c.Before == nil {
t.Fatalf("Command %s expects to have a Before func since it is a leaf command", cmdPath)
}
}
// Test subcommands
for _, subCmd := range c.Subcommands {
checkCmd(cmdPath+"/"+subCmd.Name, subCmd)
}
}
for _, cmd := range appCmds {
checkCmd("", cmd)
}
}
+1 -1
View File
@@ -49,7 +49,7 @@ var mbCmd = cli.Command{
Name: "mb",
Usage: "make a bucket",
Action: mainMakeBucket,
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Flags: append(mbFlags, globalFlags...),
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
+2 -2
View File
@@ -31,7 +31,7 @@ import (
"github.com/minio/cli"
json "github.com/minio/mc/pkg/colorjson"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio-go/v7/pkg/encrypt"
"github.com/minio/minio-go/v6/pkg/encrypt"
"github.com/minio/minio/pkg/console"
)
@@ -117,7 +117,7 @@ var mirrorCmd = cli.Command{
Name: "mirror",
Usage: "synchronize object(s) to a remote site",
Action: mainMirror,
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Flags: append(append(mirrorFlags, ioFlags...), globalFlags...),
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
+1 -1
View File
@@ -77,7 +77,7 @@ var mvCmd = cli.Command{
Name: "mv",
Usage: "move objects",
Action: mainMove,
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Flags: append(append(mvFlags, ioFlags...), globalFlags...),
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
+1 -1
View File
@@ -42,7 +42,7 @@ var pipeCmd = cli.Command{
Name: "pipe",
Usage: "stream STDIN to an object",
Action: mainPipe,
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Flags: append(append(pipeFlags, ioFlags...), globalFlags...),
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
+1 -1
View File
@@ -46,7 +46,7 @@ var policyCmd = cli.Command{
Name: "policy",
Usage: "manage anonymous access to buckets and objects",
Action: mainPolicy,
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Flags: append(policyFlags, globalFlags...),
CustomHelpTemplate: `Name:
{{.HelpName}} - {{.Usage}}
+1 -1
View File
@@ -47,7 +47,7 @@ var rbCmd = cli.Command{
Name: "rb",
Usage: "remove a bucket",
Action: mainRemoveBucket,
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Flags: append(rbFlags, globalFlags...),
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}

Some files were not shown because too many files have changed in this diff Show More