From 017dddef978db93294fc397f221cd283a5461e28 Mon Sep 17 00:00:00 2001 From: "A. Elleuch" Date: Thu, 1 Feb 2018 19:32:22 +0100 Subject: [PATCH] Add --newer-than & --older-than flags (#2142) Use --newer-than & --older-than to select newer or older files in copy, remove and mirroring operations. --- cmd/cp-main.go | 40 +++++++++++++++++++++++++--- cmd/mirror-main.go | 49 ++++++++++++++++++++++++++++------ cmd/rm-main.go | 66 ++++++++++++++++++++++++++-------------------- cmd/utils.go | 12 +++++++++ 4 files changed, 128 insertions(+), 39 deletions(-) diff --git a/cmd/cp-main.go b/cmd/cp-main.go index 965f8151..e20d7b4e 100644 --- a/cmd/cp-main.go +++ b/cmd/cp-main.go @@ -41,6 +41,14 @@ var ( Name: "recursive, r", Usage: "Copy recursively.", }, + cli.IntFlag{ + Name: "older-than", + Usage: "Copy objects older than N days", + }, + cli.IntFlag{ + Name: "newer-than", + Usage: "Copy objects newer than N days", + }, } ) @@ -74,10 +82,16 @@ EXAMPLES: 4. Copy a bucket recursively from aliased Amazon S3 cloud storage to local filesystem on Windows. $ {{.HelpName}} --recursive s3\documents\2014\ C:\Backups\2014 - 5. Copy an object with name containing unicode characters to Amazon S3 cloud storage. + 5. Copy files older than 7 days from Minio cloud storage to Amazon S3 cloud storage. + $ {{.HelpName}} --older-than 7 play/mybucket/burningman2011/ s3/mybucket/ + + 6. Copy files newer than 7 days from Minio cloud storage to a local path. + $ {{.HelpName}} --newer-than 7 play/mybucket/burningman2011/ ~/latest/ + + 7. Copy an object with name containing unicode characters to Amazon S3 cloud storage. $ {{.HelpName}} 本語 s3/andoria/ - 6. Copy a local folder with space separated characters to Amazon S3 cloud storage. + 8. Copy a local folder with space separated characters to Amazon S3 cloud storage. $ {{.HelpName}} --recursive 'workdir/documents/May 2014/' s3/miniocloud `, @@ -190,6 +204,9 @@ func doPrepareCopyURLs(session *sessionV8, trapCh <-chan bool, cancelCopy contex // Access recursive flag inside the session header. isRecursive := session.Header.CommandBoolFlags["recursive"] + olderThan := session.Header.CommandIntFlags["older-than"] + newerThan := session.Header.CommandIntFlags["newer-than"] + // Create a session data file to store the processed URLs. dataFP := session.NewDataWriter() @@ -225,6 +242,17 @@ func doPrepareCopyURLs(session *sessionV8, trapCh <-chan bool, cancelCopy contex session.Delete() fatalIf(probe.NewError(e), "Unable to prepare URL for copying. Error in JSON marshaling.") } + + // Skip objects older than --older-than parameter if specified + if olderThan > 0 && isOlder(cpURLs.SourceContent, olderThan) { + continue + } + + // Skip objects newer than --newer-than parameter if specified + if newerThan > 0 && isNewer(cpURLs.SourceContent, newerThan) { + continue + } + fmt.Fprintln(dataFP, string(jsonData)) if !globalQuiet && !globalJSON { scanBar(cpURLs.SourceContent.URL.String()) @@ -376,9 +404,15 @@ func mainCopy(ctx *cli.Context) error { // Additional command speific theme customization. console.SetColor("Copy", color.New(color.FgGreen, color.Bold)) + recursive := ctx.Bool("recursive") + olderThan := ctx.Int("older-than") + newerThan := ctx.Int("newer-than") + session := newSessionV8() session.Header.CommandType = "cp" - session.Header.CommandBoolFlags["recursive"] = ctx.Bool("recursive") + session.Header.CommandBoolFlags["recursive"] = recursive + session.Header.CommandIntFlags["older-than"] = olderThan + session.Header.CommandIntFlags["newer-than"] = newerThan var e error if session.Header.RootPath, e = os.Getwd(); e != nil { diff --git a/cmd/mirror-main.go b/cmd/mirror-main.go index 0081c8c0..495c1ffb 100644 --- a/cmd/mirror-main.go +++ b/cmd/mirror-main.go @@ -70,6 +70,14 @@ var ( Name: "exclude", Usage: "Exclude file/object that matches the passed file name pattern.", }, + cli.IntFlag{ + Name: "older-than", + Usage: "Select objects older than N days", + }, + cli.IntFlag{ + Name: "newer-than", + Usage: "Select objects newer than N days", + }, } ) @@ -97,24 +105,33 @@ EXAMPLES: 2. Mirror a local folder recursively to Amazon S3 cloud storage. $ {{.HelpName}} backup/ s3/archive - 3. Mirror a bucket from aliased Amazon S3 cloud storage to a folder on Windows. + 3. Only mirror files that are newer than 7 days to Amazon S3 cloud storage. + $ {{.HelpName}} --newer-than 7 backup/ s3/archive + + 4. Mirror a bucket from aliased Amazon S3 cloud storage to a folder on Windows. $ {{.HelpName}} s3\documents\2014\ C:\backup\2014 - 4. Mirror a bucket from aliased Amazon S3 cloud storage to a local folder use '--overwrite' to overwrite destination. + 5. Mirror a bucket from aliased Amazon S3 cloud storage to a local folder use '--overwrite' to overwrite destination. $ {{.HelpName}} --overwrite s3/miniocloud miniocloud-backup - 5. Mirror a bucket from Minio cloud storage to a bucket on Amazon S3 cloud storage and remove any extraneous + 6. Mirror a bucket from Minio cloud storage to a bucket on Amazon S3 cloud storage and remove any extraneous files on Amazon S3 cloud storage. $ {{.HelpName}} --remove play/photos/2014 s3/backup-photos/2014 - 6. Continuously mirror a local folder recursively to Minio cloud storage. '--watch' continuously watches for + 7. Continuously mirror a local folder recursively to Minio cloud storage. '--watch' continuously watches for new objects, uploads and removes extraneous files on Amazon S3 cloud storage. $ {{.HelpName}} --remove --watch /var/lib/backups play/backups - 7. Mirror a bucket from aliased Amazon S3 cloud storage to a local folder. + 8. Mirror a bucket from aliased Amazon S3 cloud storage to a local folder. Exclude all .* files and *.temp files when mirroring. $ {{.HelpName}} --exclude ".*" --exclude "*.temp" s3/test ~/test + 9. Mirror objects newer than 10 days from bucket test to a local folder. + $ {{.HelpName}} --newer-than=10 s3/test ~/localfolder + + 10. Mirror a bucket older than 30 days from Amazon S3 bucket test to a local folder. + $ {{.HelpName}} --older-than=30 s3/test ~/test + `, } @@ -152,6 +169,7 @@ type mirrorJob struct { targetURL string isFake, isRemove, isOverwrite, isWatch bool + olderThan, newerThan int excludeOptions []string } @@ -193,7 +211,7 @@ func (mj *mirrorJob) doRemove(sURLs URLs) URLs { targetWithAlias := filepath.Join(sURLs.TargetAlias, sURLs.TargetContent.URL.Path) // Remove extraneous file on target. - err := probe.NewError(removeSingle(targetWithAlias, isIncomplete, mj.isFake, 0)) + err := probe.NewError(removeSingle(targetWithAlias, isIncomplete, mj.isFake, 0, 0)) return sURLs.WithError(err) } @@ -449,7 +467,18 @@ func (mj *mirrorJob) startMirror(ctx context.Context, cancelMirror context.Cance } continue } + if sURLs.SourceContent != nil { + // Skip objects older than --older-than parameter if specified + if mj.olderThan > 0 && isOlder(sURLs.SourceContent, mj.olderThan) { + continue + } + + // Skip objects newer than --newer-than parameter if specified + if mj.newerThan > 0 && isNewer(sURLs.SourceContent, mj.newerThan) { + continue + } + // copy totalBytes += sURLs.SourceContent.Size } @@ -513,7 +542,7 @@ func (mj *mirrorJob) mirror(ctx context.Context, cancelMirror context.CancelFunc return nil } -func newMirrorJob(srcURL, dstURL string, isFake, isRemove, isOverwrite, isWatch bool, excludeOptions []string) *mirrorJob { +func newMirrorJob(srcURL, dstURL string, isFake, isRemove, isOverwrite, isWatch bool, excludeOptions []string, olderThan, newerThan int) *mirrorJob { // we'll define the status to use here, // do we want the quiet status? or the progressbar var status = NewProgressStatus() @@ -535,6 +564,8 @@ func newMirrorJob(srcURL, dstURL string, isFake, isRemove, isOverwrite, isWatch isOverwrite: isOverwrite, isWatch: isWatch, excludeOptions: excludeOptions, + olderThan: olderThan, + newerThan: newerThan, status: status, statusCh: make(chan URLs), @@ -585,7 +616,9 @@ func runMirror(srcURL, dstURL string, ctx *cli.Context) *probe.Error { ctx.Bool("remove"), isOverwrite, ctx.Bool("watch"), - ctx.StringSlice("exclude")) + ctx.StringSlice("exclude"), + ctx.Int("older-than"), + ctx.Int("newer-than")) srcClt, err := newClient(srcURL) fatalIf(err, "Unable to initialize `"+srcURL+"`") diff --git a/cmd/rm-main.go b/cmd/rm-main.go index cfc0396b..acbfcd52 100644 --- a/cmd/rm-main.go +++ b/cmd/rm-main.go @@ -63,7 +63,11 @@ var ( }, cli.IntFlag{ Name: "older-than", - Usage: "Remove objects older than N days.", + Usage: "Remove objects older than N days", + }, + cli.IntFlag{ + Name: "newer-than", + Usage: "Remove objects newer than N days", }, } ) @@ -94,16 +98,19 @@ EXAMPLES: 3. Remove all objects older than '90' days recursively from bucket 'jazz-songs' that match 'louis' prefix. $ {{.HelpName}} --recursive --older-than=90 s3/jazz-songs/louis/ - 4. Remove all objects read from STDIN. + 4. Remove all objects newer than 7 days recursively from bucket 'pop-songs' + $ {{.HelpName}} --recursive --newer-than=7 s3/pop-songs/ + + 5. Remove all objects read from STDIN. $ {{.HelpName}} --force --stdin - 5. Remove all buckets and objects recursively from S3 host + 6. Remove all buckets and objects recursively from S3 host $ {{.HelpName}} --recursive --dangerous s3 - 6. Remove all buckets and objects older than '90' days recursively from host + 7. Remove all buckets and objects older than '90' days recursively from host $ {{.HelpName}} --recursive --dangerous --older-than=90 s3 - 7. Drop all incomplete uploads on 'jazz-songs' bucket. + 8. Drop all incomplete uploads on 'jazz-songs' bucket. $ {{.HelpName}} --incomplete --recursive s3/jazz-songs/ `, @@ -166,7 +173,7 @@ func checkRmSyntax(ctx *cli.Context) { } } -func removeSingle(url string, isIncomplete bool, isFake bool, older int) error { +func removeSingle(url string, isIncomplete bool, isFake bool, olderThan int, newerThan int) error { targetAlias, targetURL, _ := mustExpandAlias(url) clnt, pErr := newClientFromAlias(targetAlias, targetURL) if pErr != nil { @@ -179,14 +186,15 @@ func removeSingle(url string, isIncomplete bool, isFake bool, older int) error { errorIf(pErr.Trace(url), "Failed to remove `"+url+"`.") return exitStatus(globalErrorExitStatus) } - if older > 0 { - // Check whether object is created older than given time. - now := UTCNow() - timeDiff := now.Sub(content.Time) - if timeDiff < (time.Duration(older) * Day) { - // time difference of info.Time with current time is less than older time. - return nil - } + + // Skip objects older than older--than parameter if specified + if olderThan > 0 && isOlder(content, olderThan) { + return nil + } + + // Skip objects older than older--than parameter if specified + if newerThan > 0 && isNewer(content, newerThan) { + return nil } printMsg(rmMessage{ @@ -215,7 +223,7 @@ func removeSingle(url string, isIncomplete bool, isFake bool, older int) error { return nil } -func removeRecursive(url string, isIncomplete bool, isFake bool, older int) error { +func removeRecursive(url string, isIncomplete bool, isFake bool, olderThan int, newerThan int) error { targetAlias, targetURL, _ := mustExpandAlias(url) clnt, pErr := newClientFromAlias(targetAlias, targetURL) if pErr != nil { @@ -241,15 +249,16 @@ func removeRecursive(url string, isIncomplete bool, isFake bool, older int) erro } urlString := content.URL.Path - if older > 0 { - // Check whether object is created older than given time. - now := UTCNow() - timeDiff := now.Sub(content.Time) - if timeDiff < (time.Duration(older) * Day) { - // time difference of info.Time with current time is less than older time. - continue - } + // Skip objects older than --older-than parameter if specified + if olderThan > 0 && isOlder(content, olderThan) { + continue } + + // Skip objects newer than --newer-than parameter if specified + if newerThan > 0 && isNewer(content, newerThan) { + continue + } + // list internally mimics recursive directory listing of object prefixes for s3 similar to FS. // The rmMessage needs to be printed only for actual objects being deleted and not prefixes. if !(content.Time.IsZero() && strings.HasSuffix(urlString, string(filepath.Separator))) { @@ -307,7 +316,8 @@ func mainRm(ctx *cli.Context) error { isRecursive := ctx.Bool("recursive") isFake := ctx.Bool("fake") isStdin := ctx.Bool("stdin") - older := ctx.Int("older-than") + olderThan := ctx.Int("older-than") + newerThan := ctx.Int("newer-than") // Set color. console.SetColor("Remove", color.New(color.FgGreen, color.Bold)) @@ -317,9 +327,9 @@ func mainRm(ctx *cli.Context) error { // Support multiple targets. for _, url := range ctx.Args() { if isRecursive { - err = removeRecursive(url, isIncomplete, isFake, older) + err = removeRecursive(url, isIncomplete, isFake, olderThan, newerThan) } else { - err = removeSingle(url, isIncomplete, isFake, older) + err = removeSingle(url, isIncomplete, isFake, olderThan, newerThan) } if rerr == nil { @@ -335,9 +345,9 @@ func mainRm(ctx *cli.Context) error { for scanner.Scan() { url := scanner.Text() if isRecursive { - err = removeRecursive(url, isIncomplete, isFake, older) + err = removeRecursive(url, isIncomplete, isFake, olderThan, newerThan) } else { - err = removeSingle(url, isIncomplete, isFake, older) + err = removeSingle(url, isIncomplete, isFake, olderThan, newerThan) } if rerr == nil { diff --git a/cmd/utils.go b/cmd/utils.go index a0b8d80e..0ea7d128 100644 --- a/cmd/utils.go +++ b/cmd/utils.go @@ -130,3 +130,15 @@ func lineTrunc(content string, maxLen int) string { sndPart := string(runes[rlen-halfLen:]) return fstPart + "…" + sndPart } + +// isOlder returns true if the passed object is older than olderRef +func isOlder(c *clientContent, olderRef int) bool { + objectAge := UTCNow().Sub(c.Time) + return objectAge < (time.Duration(olderRef) * Day) +} + +// isNewer returns true if the passed object is newer than newerRef +func isNewer(c *clientContent, newerRef int) bool { + objectAge := UTCNow().Sub(c.Time) + return objectAge > (time.Duration(newerRef) * Day) +}