Refactor rm command. (#1855)

This patch makes rm command to use minio-go.RemoveObjects() to removeobjects recursively.
This commit is contained in:
Bala FA
2016-10-17 20:24:09 -07:00
committed by Harshavardhana
parent 0661f537cf
commit 6de2b4559e
16 changed files with 806 additions and 251 deletions
+122 -14
View File
@@ -464,21 +464,48 @@ func (f *fsClient) Get() (io.Reader, *probe.Error) {
return fileData, nil
}
// Remove - remove the path.
func (f *fsClient) Remove(incomplete bool) *probe.Error {
e := os.Remove(f.PathURL.Path)
err := f.toClientError(e, f.PathURL.Path)
return err.Trace(f.PathURL.Path)
// Remove - remove entry read from clientContent channel.
func (f *fsClient) Remove(isIncomplete bool, contentCh <-chan *clientContent) <-chan *probe.Error {
errorCh := make(chan *probe.Error)
// Goroutine reads from contentCh and removes the entry in content.
go func() {
defer close(errorCh)
for content := range contentCh {
name := content.URL.Path
// Add partSuffix for incomplete uploads.
if isIncomplete {
name += partSuffix
}
if err := os.Remove(name); err != nil {
if os.IsPermission(err) {
// Ignore permission error.
errorCh <- probe.NewError(PathInsufficientPermission{Path: content.URL.Path})
} else {
errorCh <- probe.NewError(err)
return
}
}
}
}()
return errorCh
}
// List - list files and folders.
func (f *fsClient) List(recursive, incomplete bool) <-chan *clientContent {
func (f *fsClient) List(isRecursive, isIncomplete bool, showDir DirOpt) <-chan *clientContent {
contentCh := make(chan *clientContent)
if recursive {
go f.listRecursiveInRoutine(contentCh, incomplete)
if isRecursive {
if showDir == DirNone {
go f.listRecursiveInRoutine(contentCh, isIncomplete)
} else {
go f.listDirOpt(contentCh, isIncomplete, showDir)
}
} else {
go f.listInRoutine(contentCh, incomplete)
go f.listInRoutine(contentCh, isIncomplete)
}
return contentCh
}
@@ -649,7 +676,7 @@ func (f *fsClient) listInRoutine(contentCh chan<- *clientContent, incomplete boo
pathURL := *f.PathURL
fpath := pathURL.Path
fst, err := f.fsStat()
fst, err := f.fsStat(false)
if err != nil {
if _, ok := err.ToGoError().(PathNotFound); ok {
// If file does not exist treat it like a prefix and list all prefixes if any.
@@ -781,6 +808,84 @@ func (f *fsClient) listInRoutine(contentCh chan<- *clientContent, incomplete boo
}
}
// List files recursively using non-recursive mode.
func (f *fsClient) listDirOpt(contentCh chan *clientContent, isIncomplete bool, dirOpt DirOpt) {
defer close(contentCh)
// Trim trailing / or \.
currentPath := f.PathURL.Path
currentPath = strings.TrimSuffix(currentPath, "/")
if runtime.GOOS == "windows" {
currentPath = strings.TrimSuffix(currentPath, `\`)
}
// Closure function reads currentPath and sends to contentCh. If a directory is found, it lists the directory content recursively.
var listDir func(currentPath string) bool
listDir = func(currentPath string) (isStop bool) {
files, err := readDir(currentPath)
if err != nil {
if os.IsPermission(err) {
contentCh <- &clientContent{Err: probe.NewError(PathInsufficientPermission{Path: currentPath})}
return false
}
contentCh <- &clientContent{Err: probe.NewError(err)}
return true
}
for _, file := range files {
name := filepath.Join(currentPath, file.Name())
content := clientContent{
URL: *newClientURL(name),
Time: file.ModTime(),
Size: file.Size(),
Type: file.Mode(),
Err: nil,
}
if file.Mode().IsDir() {
if dirOpt == DirFirst && !isIncomplete {
contentCh <- &content
}
if listDir(filepath.Join(name)) {
return true
}
if dirOpt == DirLast && !isIncomplete {
contentCh <- &content
}
continue
}
if isIncomplete {
// Ignore if file name does not end with partSuffix.
if !strings.HasSuffix(file.Name(), partSuffix) {
continue
}
// Strip partSuffix
name = strings.SplitAfter(name, partSuffix)[0]
content.URL = *newClientURL(name)
}
contentCh <- &content
}
return false
}
// listDir() does not send currentPath to contentCh. We send it here depending on dirOpt.
if dirOpt == DirFirst && !isIncomplete {
contentCh <- &clientContent{URL: *newClientURL(currentPath), Type: os.ModeDir}
}
listDir(currentPath)
if dirOpt == DirLast && !isIncomplete {
contentCh <- &clientContent{URL: *newClientURL(currentPath), Type: os.ModeDir}
}
}
func (f *fsClient) listRecursiveInRoutine(contentCh chan *clientContent, incomplete bool) {
// close channels upon return.
defer close(contentCh)
@@ -992,7 +1097,7 @@ func (f *fsClient) GetAccess() (access string, err *probe.Error) {
if runtime.GOOS == "windows" {
return "", probe.NewError(APINotImplemented{API: "GetAccess", APIType: "filesystem"})
}
st, err := f.fsStat()
st, err := f.fsStat(false)
if err != nil {
return "", err.Trace(f.PathURL.String())
}
@@ -1016,7 +1121,7 @@ func (f *fsClient) SetAccess(access string) *probe.Error {
if runtime.GOOS == "windows" {
return probe.NewError(APINotImplemented{API: "SetAccess", APIType: "filesystem"})
}
st, err := f.fsStat()
st, err := f.fsStat(false)
if err != nil {
return err.Trace(f.PathURL.String())
}
@@ -1043,7 +1148,7 @@ func (f *fsClient) SetAccess(access string) *probe.Error {
// Stat - get metadata from path.
func (f *fsClient) Stat(isIncomplete bool) (content *clientContent, err *probe.Error) {
st, err := f.fsStat()
st, err := f.fsStat(isIncomplete)
if err != nil {
return nil, err.Trace(f.PathURL.String())
}
@@ -1080,8 +1185,11 @@ func (f *fsClient) handleWindowsSymlinks(fpath string) (os.FileInfo, *probe.Erro
}
// fsStat - wrapper function to get file stat.
func (f *fsClient) fsStat() (os.FileInfo, *probe.Error) {
func (f *fsClient) fsStat(isIncomplete bool) (os.FileInfo, *probe.Error) {
fpath := f.PathURL.Path
if isIncomplete {
fpath += partSuffix
}
// Golang strips trailing / if you clean(..) or
// EvalSymlinks(..). Adding '.' prevents it from doing so.
if strings.HasSuffix(fpath, string(f.PathURL.Separator)) {
+4 -4
View File
@@ -60,7 +60,7 @@ func (s *TestSuite) TestList(c *C) {
// Verify previously create files and list them.
var contents []*clientContent
for content := range fsClient.List(false, false) {
for content := range fsClient.List(false, false, DirNone) {
if content.Err != nil {
err = content.Err
break
@@ -86,7 +86,7 @@ func (s *TestSuite) TestList(c *C) {
contents = nil
// List non recursive to list only top level files.
for content := range fsClient.List(false, false) {
for content := range fsClient.List(false, false, DirNone) {
if content.Err != nil {
err = content.Err
break
@@ -102,7 +102,7 @@ func (s *TestSuite) TestList(c *C) {
contents = nil
// List recursively all files and verify.
for content := range fsClient.List(true, false) {
for content := range fsClient.List(true, false, DirNone) {
if content.Err != nil {
err = content.Err
break
@@ -144,7 +144,7 @@ func (s *TestSuite) TestList(c *C) {
contents = nil
// List recursively all files and verify.
for content := range fsClient.List(true, false) {
for content := range fsClient.List(true, false, DirNone) {
if content.Err != nil {
err = content.Err
break
+353 -20
View File
@@ -567,21 +567,101 @@ func (c *s3Client) Put(reader io.Reader, size int64, contentType string, progres
return n, nil
}
// Remove incomplete uploads.
func (c *s3Client) removeIncomplete(bucket string, objectsCh <-chan string) <-chan minio.RemoveObjectError {
removeObjectErrorCh := make(chan minio.RemoveObjectError)
// Goroutine reads from objectsCh and sends error to removeObjectErrorCh if any.
go func() {
defer close(removeObjectErrorCh)
for object := range objectsCh {
if err := c.api.RemoveIncompleteUpload(bucket, object); err != nil {
removeObjectErrorCh <- minio.RemoveObjectError{ObjectName: object, Err: err}
}
}
}()
return removeObjectErrorCh
}
// Remove - remove object or bucket.
func (c *s3Client) Remove(incomplete bool) *probe.Error {
bucket, object := c.url2BucketAndObject()
// Remove only incomplete object.
if incomplete && object != "" {
e := c.api.RemoveIncompleteUpload(bucket, object)
return probe.NewError(e)
}
var e error
if object == "" {
e = c.api.RemoveBucket(bucket)
} else {
e = c.api.RemoveObject(bucket, object)
}
return probe.NewError(e)
func (c *s3Client) Remove(isIncomplete bool, contentCh <-chan *clientContent) <-chan *probe.Error {
bucket, _ := c.url2BucketAndObject()
errorCh := make(chan *probe.Error)
var bucketContent *clientContent
// Goroutine
// 1. calls removeIncomplete() for incomplete uploads or minio-go.RemoveObjects().
// 2. executes another Goroutine to copy contentCh to objectsCh.
// 3. reads statusCh and copies to errorCh.
go func() {
defer close(errorCh)
objectsCh := make(chan string)
var statusCh <-chan minio.RemoveObjectError
if isIncomplete {
statusCh = c.removeIncomplete(bucket, objectsCh)
} else {
statusCh = c.api.RemoveObjects(bucket, objectsCh)
}
// doneCh to control below Goroutine.
doneCh := make(chan struct{})
defer close(doneCh)
// Goroutine reads contentCh and copies to objectsCh.
go func() {
defer close(objectsCh)
for {
// Read from contentCh or doneCh. If doneCh is read, exit the function.
var content *clientContent
var ok bool
select {
case content, ok = <-contentCh:
if !ok {
// Closed channel.
return
}
case <-doneCh:
return
}
// Convert content.URL.Path to objectName for objectsCh.
_, objectName := c.splitPath(content.URL.Path)
objectName = strings.TrimSuffix(objectName, string(c.targetURL.Separator))
// As object name is empty, we need to remove the bucket as well.
if objectName == "" {
bucketContent = content
continue
}
// Write to objectsCh or read doneCh. If doneCh is read, exit the function.
select {
case objectsCh <- objectName:
case <-doneCh:
return
}
}
}()
// Read statusCh and write to errorCh.
for removeStatus := range statusCh {
errorCh <- probe.NewError(removeStatus.Err)
}
// Remove bucket for regular objects.
if bucketContent != nil && !isIncomplete {
if err := c.api.RemoveBucket(bucket); err != nil {
errorCh <- probe.NewError(err)
}
}
}()
return errorCh
}
// We support '.' with bucket names but we fallback to using path
@@ -801,27 +881,62 @@ func (c *s3Client) url2BucketAndObject() (bucketName, objectName string) {
return bucketName, objectName
}
// splitPath split path into bucket and object.
func (c *s3Client) splitPath(path string) (bucketName, objectName string) {
path = strings.TrimPrefix(path, string(c.targetURL.Separator))
// Handle path if its virtual style.
if c.virtualStyle {
hostIndex := strings.Index(c.targetURL.Host, "s3")
if hostIndex == -1 {
hostIndex = strings.Index(c.targetURL.Host, "storage.googleapis")
}
if hostIndex > 0 {
bucketName = c.targetURL.Host[:hostIndex-1]
objectName = path
return bucketName, objectName
}
}
tokens := strings.SplitN(path, string(c.targetURL.Separator), 2)
bucketName = tokens[0]
if len(tokens) == 2 {
objectName = tokens[1]
}
return bucketName, objectName
}
/// Bucket API operations.
// List - list at delimited path, if not recursive.
func (c *s3Client) List(recursive, incomplete bool) <-chan *clientContent {
func (c *s3Client) List(isRecursive, isIncomplete bool, showDir DirOpt) <-chan *clientContent {
c.mutex.Lock()
defer c.mutex.Unlock()
contentCh := make(chan *clientContent)
if incomplete {
if recursive {
go c.listIncompleteRecursiveInRoutine(contentCh)
if isIncomplete {
if isRecursive {
if showDir == DirNone {
go c.listIncompleteRecursiveInRoutine(contentCh)
} else {
go c.listIncompleteRecursiveInRoutineDirOpt(contentCh, showDir)
}
} else {
go c.listIncompleteInRoutine(contentCh)
}
} else {
if recursive {
go c.listRecursiveInRoutine(contentCh)
if isRecursive {
if showDir == DirNone {
go c.listRecursiveInRoutine(contentCh)
} else {
go c.listRecursiveInRoutineDirOpt(contentCh, showDir)
}
} else {
go c.listInRoutine(contentCh)
}
}
return contentCh
}
@@ -959,6 +1074,224 @@ func (c *s3Client) listIncompleteRecursiveInRoutine(contentCh chan *clientConten
}
}
// Convert objectMultipartInfo to clientContent
func (c *s3Client) objectMultipartInfo2ClientContent(entry minio.ObjectMultipartInfo) clientContent {
bucket, _ := c.url2BucketAndObject()
content := clientContent{}
url := *c.targetURL
// Join bucket and incoming object key.
url.Path = filepath.Join(string(url.Separator), bucket, entry.Key)
if c.virtualStyle {
url.Path = filepath.Join(string(url.Separator), entry.Key)
}
content.URL = url
content.Size = entry.Size
content.Time = entry.Initiated
if strings.HasSuffix(entry.Key, "/") {
content.Type = os.ModeDir
} else {
content.Type = os.ModeTemporary
}
return content
}
// Recursively lists incomplete uploads.
func (c *s3Client) listIncompleteRecursiveInRoutineDirOpt(contentCh chan *clientContent, dirOpt DirOpt) {
defer close(contentCh)
// Closure function reads list of incomplete uploads and sends to contentCh. If a directory is found, it lists
// incomplete uploads of the directory content recursively.
var listDir func(bucket, object string) bool
listDir = func(bucket, object string) (isStop bool) {
isRecursive := false
for entry := range c.api.ListIncompleteUploads(bucket, object, isRecursive, nil) {
if entry.Err != nil {
url := *c.targetURL
url.Path = filepath.Join(string(url.Separator), bucket, object)
if c.virtualStyle {
url.Path = filepath.Join(string(url.Separator), object)
}
contentCh <- &clientContent{URL: url, Err: probe.NewError(entry.Err)}
errResponse := minio.ToErrorResponse(entry.Err)
if errResponse.Code == "AccessDenied" {
continue
}
return true
}
content := c.objectMultipartInfo2ClientContent(entry)
// Handle if object.Key is a directory.
if strings.HasSuffix(entry.Key, string(c.targetURL.Separator)) {
if dirOpt == DirFirst {
contentCh <- &content
}
if listDir(bucket, entry.Key) {
return true
}
if dirOpt == DirLast {
contentCh <- &content
}
} else {
contentCh <- &content
}
}
return false
}
bucket, object := c.url2BucketAndObject()
listDir(bucket, object)
}
// Returns new path by joining path segments with URL path separator.
func (c *s3Client) joinPath(segments ...string) string {
var retPath string
pathSep := string(c.targetURL.Separator)
for _, segment := range segments {
segment = strings.TrimPrefix(segment, pathSep)
if !strings.HasSuffix(retPath, pathSep) {
retPath += pathSep
}
retPath += segment
}
return retPath
}
// Convert objectInfo to clientContent
func (c *s3Client) objectInfo2ClientContent(entry minio.ObjectInfo) clientContent {
bucket, _ := c.url2BucketAndObject()
content := clientContent{}
url := *c.targetURL
// Join bucket and incoming object key.
url.Path = c.joinPath(bucket, entry.Key)
// If virtualStyle replace the url.Path back.
if c.virtualStyle {
url.Path = c.joinPath(entry.Key)
}
content.URL = url
content.Size = entry.Size
content.Time = entry.LastModified
if strings.HasSuffix(entry.Key, "/") && entry.Size == 0 && entry.LastModified.IsZero() {
content.Type = os.ModeDir
} else {
content.Type = os.FileMode(0664)
}
return content
}
// Returns bucket stat info of current bucket.
func (c *s3Client) bucketStat() clientContent {
bucketName, _ := c.url2BucketAndObject()
buckets, err := c.api.ListBuckets()
if err != nil {
return clientContent{Err: probe.NewError(err)}
}
for _, bucket := range buckets {
if bucket.Name == bucketName {
return clientContent{URL: *c.targetURL, Time: bucket.CreationDate, Type: os.ModeDir}
}
}
return clientContent{Err: probe.NewError(BucketDoesNotExist{Bucket: bucketName})}
}
// Recursively lists objects.
func (c *s3Client) listRecursiveInRoutineDirOpt(contentCh chan *clientContent, dirOpt DirOpt) {
defer close(contentCh)
// Closure function reads list objects and sends to contentCh. If a directory is found, it lists
// objects of the directory content recursively.
var listDir func(bucket, object string) bool
listDir = func(bucket, object string) (isStop bool) {
isRecursive := false
for entry := range c.listObjectWrapper(bucket, object, isRecursive, nil) {
if entry.Err != nil {
url := *c.targetURL
url.Path = c.joinPath(bucket, object)
if c.virtualStyle {
url.Path = c.joinPath(object)
}
contentCh <- &clientContent{URL: url, Err: probe.NewError(entry.Err)}
errResponse := minio.ToErrorResponse(entry.Err)
if errResponse.Code == "AccessDenied" {
continue
}
return true
}
content := c.objectInfo2ClientContent(entry)
// Handle if object.Key is a directory.
if content.Type.IsDir() {
if dirOpt == DirFirst {
contentCh <- &content
}
if listDir(bucket, entry.Key) {
return true
}
if dirOpt == DirLast {
contentCh <- &content
}
} else {
contentCh <- &content
}
}
return false
}
bucket, object := c.url2BucketAndObject()
var cContent *clientContent
// Get bucket stat if object is empty.
if object == "" {
content := c.bucketStat()
cContent = &content
if content.Err != nil {
contentCh <- cContent
return
}
} else if strings.HasSuffix(object, string(c.targetURL.Separator)) {
// Get stat of given object is a directory.
isIncomplete := false
content, perr := c.Stat(isIncomplete)
cContent = content
if perr != nil {
contentCh <- &clientContent{URL: *c.targetURL, Err: perr}
return
}
}
if cContent != nil && dirOpt == DirFirst {
contentCh <- cContent
}
listDir(bucket, object)
if cContent != nil && dirOpt == DirLast {
contentCh <- cContent
}
}
func (c *s3Client) listInRoutine(contentCh chan *clientContent) {
defer close(contentCh)
// get bucket and object from URL.
+3 -3
View File
@@ -181,7 +181,7 @@ func (s *TestSuite) TestBucketOperations(c *C) {
s3c, err = s3New(conf)
c.Assert(err, IsNil)
for content := range s3c.List(false, false) {
for content := range s3c.List(false, false, DirNone) {
c.Assert(content.Err, IsNil)
c.Assert(content.Type.IsDir(), Equals, true)
}
@@ -190,7 +190,7 @@ func (s *TestSuite) TestBucketOperations(c *C) {
s3c, err = s3New(conf)
c.Assert(err, IsNil)
for content := range s3c.List(false, false) {
for content := range s3c.List(false, false, DirNone) {
c.Assert(content.Err, IsNil)
c.Assert(content.Type.IsDir(), Equals, true)
}
@@ -199,7 +199,7 @@ func (s *TestSuite) TestBucketOperations(c *C) {
s3c, err = s3New(conf)
c.Assert(err, IsNil)
for content := range s3c.List(false, false) {
for content := range s3c.List(false, false, DirNone) {
c.Assert(content.Err, IsNil)
c.Assert(content.Type.IsRegular(), Equals, true)
}
+1 -1
View File
@@ -221,7 +221,7 @@ func isURLPrefixExists(urlPrefix string, incomplete bool) bool {
}
isRecursive := false
isIncomplete := incomplete
for entry := range clnt.List(isRecursive, isIncomplete) {
for entry := range clnt.List(isRecursive, isIncomplete, DirNone) {
return entry.Err == nil
}
return false
+14 -2
View File
@@ -24,11 +24,23 @@ import (
"github.com/minio/minio/pkg/probe"
)
// DirOpt - list directory option.
type DirOpt int8
const (
// DirNone - do not include directories in the list.
DirNone DirOpt = iota
// DirFirst - include directories before objects in the list.
DirFirst
// DirLast - include directories after objects in the list.
DirLast
)
// Client - client interface
type Client interface {
// Common operations
Stat(isIncomplete bool) (content *clientContent, err *probe.Error)
List(recursive, incomplete bool) <-chan *clientContent
List(isRecursive, isIncomplete bool, showDir DirOpt) <-chan *clientContent
// Bucket operations
MakeBucket(region string) *probe.Error
@@ -52,7 +64,7 @@ type Client interface {
Unwatch(params watchParams) *probe.Error
// Delete operations
Remove(incomplete bool) *probe.Error
Remove(isIncomplete bool, contentCh <-chan *clientContent) (errorCh <-chan *probe.Error)
// GetURL returns back internal url
GetURL() clientURL
+2 -1
View File
@@ -168,7 +168,8 @@ func prepareCopyURLsTypeC(sourceURL, targetURL string, isRecursive bool) <-chan
return
}
for sourceContent := range sourceClient.List(isRecursive, false) {
isIncomplete := false
for sourceContent := range sourceClient.List(isRecursive, isIncomplete, DirNone) {
if sourceContent.Err != nil {
// Listing failed.
copyURLsCh <- URLs{Error: sourceContent.Err.Trace(sourceClient.GetURL().String())}
+2 -2
View File
@@ -61,8 +61,8 @@ func objectDifference(sourceClnt, targetClnt Client, sourceURL, targetURL string
// Set default values for listing.
isRecursive := true // recursive is always true for diff.
isIncomplete := false // we will not compare any incomplete objects.
srcCh := sourceClnt.List(isRecursive, isIncomplete)
tgtCh := targetClnt.List(isRecursive, isIncomplete)
srcCh := sourceClnt.List(isRecursive, isIncomplete, DirNone)
tgtCh := targetClnt.List(isRecursive, isIncomplete, DirNone)
diffCh = make(chan diffMessage, 1000)
+1 -1
View File
@@ -110,7 +110,7 @@ func doList(clnt Client, isRecursive, isIncomplete bool) *probe.Error {
if !strings.HasSuffix(prefixPath, separator) {
prefixPath = prefixPath[:strings.LastIndex(prefixPath, separator)+1]
}
for content := range clnt.List(isRecursive, isIncomplete) {
for content := range clnt.List(isRecursive, isIncomplete, DirNone) {
if content.Err != nil {
switch content.Err.ToGoError().(type) {
// handle this specifically for filesystem related errors.
+4 -12
View File
@@ -25,7 +25,6 @@ import (
"strings"
"sync"
"syscall"
"time"
"github.com/cheggaaa/pb"
"github.com/fatih/color"
@@ -187,17 +186,13 @@ func (ms *mirrorSession) doRemove(sURLs URLs) URLs {
return sURLs.WithError(nil)
}
targetAlias := sURLs.TargetAlias
targetURL := sURLs.TargetContent.URL
// We are not removing incomplete uploads.
isIncomplete := false
// Remove extraneous file on target.
err := rm(targetAlias, targetURL.String(), isIncomplete, isFake, time.Duration(0))
if err != nil {
return sURLs.WithError(err.Trace(targetAlias, targetURL.String()))
}
removeSingle(targetURL.String(), isIncomplete, isFake, 0)
return sURLs.WithError(nil)
}
@@ -337,10 +332,7 @@ func (ms *mirrorSession) startStatus() {
} else if sURLs.TargetContent != nil {
// Construct user facing message and path.
targetPath := filepath.ToSlash(filepath.Join(sURLs.TargetAlias, sURLs.TargetContent.URL.Path))
ms.status.PrintMsg(rmMessage{
Status: "success",
URL: targetPath,
})
ms.status.PrintMsg(rmMessage{Key: targetPath})
}
}
}()
@@ -401,9 +393,9 @@ func (ms *mirrorSession) watch() {
// If the passed source URL points to fs, fetch the absolute src path
// to correctly calculate targetPath
if sourceAlias == "" {
tmpSrcUrl, err := filepath.Abs(sourceURLFull)
tmpSrcURL, err := filepath.Abs(sourceURLFull)
if err == nil {
sourceURLFull = tmpSrcUrl
sourceURLFull = tmpSrcURL
}
}
+137 -185
View File
@@ -21,10 +21,6 @@ import (
"encoding/json"
"fmt"
"os"
"path"
"path/filepath"
"runtime"
"strings"
"time"
"github.com/fatih/color"
@@ -33,8 +29,8 @@ import (
"github.com/minio/minio/pkg/probe"
)
// default older time.
const defaultOlderTime = time.Hour
// Day time.Duration for day.
const Day = 24 * time.Hour
// rm specific flags.
var (
@@ -51,13 +47,9 @@ var (
Name: "force",
Usage: "Force a dangerous remove operation.",
},
cli.BoolFlag{
Name: "prefix",
Usage: "Remove objects matching this prefix.",
},
cli.BoolFlag{
Name: "incomplete, I",
Usage: "Remove an incomplete upload(s).",
Usage: "Remove an incomplete objects.",
},
cli.BoolFlag{
Name: "fake",
@@ -65,11 +57,11 @@ var (
},
cli.BoolFlag{
Name: "stdin",
Usage: "Read object list from STDIN.",
Usage: "Read object names from STDIN.",
},
cli.StringFlag{
Name: "older",
Usage: "Remove object only if its created older than given time.",
cli.IntFlag{
Name: "older-than",
Usage: "Remove objects older than N days.",
},
}
)
@@ -77,7 +69,7 @@ var (
// remove a file or folder.
var rmCmd = cli.Command{
Name: "rm",
Usage: "Remove file or bucket [WARNING: Use with care].",
Usage: "Remove files and objects.",
Action: mainRm,
Flags: append(rmFlags, globalFlags...),
CustomHelpTemplate: `NAME:
@@ -93,35 +85,28 @@ EXAMPLES:
1. Remove a file.
$ mc {{.Name}} 1999/old-backup.tgz
2. Remove all objects from music/ogg folder matching this prefix, excluding its sub-folders.
$ mc {{.Name}} --prefix s3/music/ogg/gunmetal
3. Remove contents of a folder, excluding its sub-folders.
$ mc {{.Name}} --prefix s3/jazz-songs/louis/
4. Remove contents of a folder recursively.
2. Remove all objects recursively.
$ mc {{.Name}} --recursive s3/jazz-songs/louis/
5. Drop an incomplete upload of an object.
$ mc {{.Name}} --incomplete s3/jazz-songs/louis/file01.mp4
3. Remove all objects older than '90' days.
$ mc {{.Name}} --recursive --older-than=90 s3/jazz-songs/louis/
6. Remove all matching objects whose names are read from STDIN.
4. Remove all objects read from STDIN.
$ mc {{.Name}} --force --stdin
7. Remove object only if its created older than one day.
$ mc {{.Name}} --force --older=24h s3/jazz-songs/louis/
5. Drop all incomplete uploads on 'jazz-songs' bucket.
$ mc {{.Name}} --incomplete --recursive s3/jazz-songs/
`,
}
// Structured message depending on the type of console.
type rmMessage struct {
Status string `json:"status"`
URL string `json:"url"`
Key string `json:"key"`
}
// Colorized message for console printing.
func (r rmMessage) String() string {
return console.Colorize("Remove", fmt.Sprintf("Removed ‘%s’.", r.URL))
return console.Colorize("Remove", fmt.Sprintf("Removing ‘%s’.", r.Key))
}
// JSON'ified message for scripting.
@@ -135,23 +120,8 @@ func (r rmMessage) JSON() string {
func checkRmSyntax(ctx *cli.Context) {
// Set command flags from context.
isForce := ctx.Bool("force")
isPrefix := ctx.Bool("prefix")
isRecursive := ctx.Bool("recursive")
isStdin := ctx.Bool("stdin")
olderString := ctx.String("older")
if olderString != "" {
if older, err := time.ParseDuration(olderString); err != nil {
fatalIf(errDummy().Trace(), "Invalid older time format.")
} else if older < defaultOlderTime {
fatalIf(errDummy().Trace(), "older time should not be less than one hour.")
}
if !isStdin && !ctx.Args().Present() {
exitCode := 1
cli.ShowCommandHelpAndExit(ctx, "rm", exitCode)
}
}
if !ctx.Args().Present() && !isStdin {
exitCode := 1
@@ -159,115 +129,132 @@ func checkRmSyntax(ctx *cli.Context) {
}
// For all recursive operations make sure to check for 'force' flag.
if (isPrefix || isRecursive || isStdin) && !isForce {
if (isRecursive || isStdin) && !isForce {
fatalIf(errDummy().Trace(),
"Removal requires --force option. This operational is irreversible. Please review carefully before performing this *DANGEROUS* operation.")
"Removal requires --force option. This operational is *IRREVERSIBLE*. Please review carefully before performing this *DANGEROUS* operation.")
}
}
// Remove a single object.
func rmObject(targetAlias, targetURL string, isIncomplete bool) *probe.Error {
clnt, err := newClientFromAlias(targetAlias, targetURL)
if err != nil {
return err.Trace(targetURL)
}
if err = clnt.Remove(isIncomplete); err != nil {
return err.Trace(targetURL)
}
return nil
}
// Remove a single object.
func rm(targetAlias, targetURL string, isIncomplete, isFake bool, older time.Duration) *probe.Error {
clnt, err := newClientFromAlias(targetAlias, targetURL)
if err != nil {
return err.Trace(targetURL)
}
// Check whether object is created older than given time only if older is >= one hour.
if older >= defaultOlderTime {
info, err := clnt.Stat(isIncomplete)
if err != nil {
return err.Trace(targetURL)
}
now := time.Now().UTC()
timeDiff := now.Sub(info.Time)
if timeDiff < older {
// time difference of info.Time with current time is less than older duration.
return nil
}
}
if !isFake {
if err := rmObject(targetAlias, targetURL, isIncomplete); err != nil {
return err.Trace(targetURL)
}
}
return nil
}
// Remove all objects recursively.
func rmAll(targetAlias, targetURL, prefix string, isRecursive, isIncomplete, isFake bool, older time.Duration) {
// Initialize new client.
clnt, err := newClientFromAlias(targetAlias, targetURL)
if err != nil {
errorIf(err.Trace(targetURL), "Invalid URL ‘"+targetURL+"’.")
func removeSingle(url string, isIncomplete bool, isFake bool, older int) {
targetAlias, targetURL, _ := mustExpandAlias(url)
clnt, pErr := newClientFromAlias(targetAlias, targetURL)
if pErr != nil {
errorIf(pErr.Trace(url), "Invalid argument ‘"+url+"’.")
return // End of journey.
}
/* Disable recursion and only list this folder's contents. We
perform manual depth-first recursion ourself here. */
nonRecursive := false
for entry := range clnt.List(nonRecursive, isIncomplete) {
if entry.Err != nil {
errorIf(entry.Err.Trace(targetURL), "Unable to list ‘"+targetURL+"’.")
return // End of journey.
if older > 0 {
content, pErr := clnt.Stat(isIncomplete)
if pErr != nil {
errorIf(pErr.Trace(url), "Failed to remove ‘"+url+"’.")
return
}
if !strings.HasPrefix(path.Base(entry.URL.Path), prefix) {
// Skip the entry if it doesn't starts with the prefix.
// Check whether object is created older than given time.
now := time.Now().UTC()
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
}
}
printMsg(rmMessage{Key: url})
if !isFake {
contentCh := make(chan *clientContent, 1)
contentCh <- &clientContent{URL: *newClientURL(targetURL)}
close(contentCh)
errorCh := clnt.Remove(isIncomplete, contentCh)
for pErr := range errorCh {
if pErr != nil {
errorIf(pErr.Trace(url), "Failed to remove ‘"+url+"’.")
switch pErr.ToGoError().(type) {
case PathInsufficientPermission:
// Ignore Permission error.
continue
}
return
}
}
}
}
func removeRecursive(url string, isIncomplete bool, isFake bool, older int) {
targetAlias, targetURL, _ := mustExpandAlias(url)
clnt, pErr := newClientFromAlias(targetAlias, targetURL)
if pErr != nil {
errorIf(pErr.Trace(url), "Failed to remove ‘"+url+"’ recursively.")
return // End of journey.
}
contentCh := make(chan *clientContent)
errorCh := clnt.Remove(isIncomplete, contentCh)
isEmpty := true
isRecursive := true
for content := range clnt.List(isRecursive, isIncomplete, DirLast) {
isEmpty = false
pErr := content.Err
if pErr != nil {
errorIf(pErr.Trace(url), "Failed to remove ‘"+url+"’ recursively.")
switch pErr.ToGoError().(type) {
case PathInsufficientPermission:
// Ignore Permission error.
continue
}
close(contentCh)
return
}
if older > 0 {
// Check whether object is created older than given time.
now := time.Now().UTC()
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
}
}
urlString := content.URL.Path
printMsg(rmMessage{Key: targetAlias + urlString})
if !isFake {
sent := false
for sent == false {
select {
case contentCh <- content:
sent = true
case pErr := <-errorCh:
errorIf(pErr.Trace(urlString), "Failed to remove ‘"+urlString+"’.")
switch pErr.ToGoError().(type) {
case PathInsufficientPermission:
// Ignore Permission error.
continue
}
close(contentCh)
return
}
}
}
}
close(contentCh)
for pErr := range errorCh {
errorIf(pErr.Trace(url), "Failed to remove ‘"+url+"’ recursively.")
switch pErr.ToGoError().(type) {
case PathInsufficientPermission:
// Ignore Permission error.
continue
}
return
}
if entry.Type.IsDir() && isRecursive {
// Add separator at the end to remove all its contents.
url := entry.URL
url.Path = strings.TrimSuffix(entry.URL.Path, string(entry.URL.Separator)) + string(entry.URL.Separator)
// Recursively remove contents of this directory.
rmAll(targetAlias, url.String(), prefix, isRecursive, isIncomplete, isFake, older)
}
// Check whether object is created older than given time only if older is >= one hour.
if older >= defaultOlderTime {
now := time.Now().UTC()
timeDiff := now.Sub(entry.Time)
if timeDiff < older {
// time difference of info.Time with current time is less than older duration.
continue
}
}
// Regular type.
if !isFake {
entryPath := entry.URL.String()
// Add '/' to force removing empty directories
if entry.Type.IsDir() {
entryPath += string(entry.URL.Separator)
}
if err = rmObject(targetAlias, entryPath, isIncomplete); err != nil {
errorIf(err.Trace(entry.URL.String()), "Unable to remove ‘"+entry.URL.String()+"’.")
continue
}
}
// Construct user facing message and path.
entryPath := filepath.ToSlash(filepath.Join(targetAlias, entry.URL.Path))
printMsg(rmMessage{Status: "success", URL: entryPath})
// As clnt.List() returns empty, we just send dummy value to behave like non-recursive.
if isEmpty {
printMsg(rmMessage{Key: url})
}
}
@@ -280,40 +267,21 @@ func mainRm(ctx *cli.Context) {
checkRmSyntax(ctx)
// rm specific flags.
isForce := ctx.Bool("force")
isPrefix := ctx.Bool("prefix")
isIncomplete := ctx.Bool("incomplete")
isRecursive := ctx.Bool("recursive")
isFake := ctx.Bool("fake")
isStdin := ctx.Bool("stdin")
olderString := ctx.String("older")
older, _ := time.ParseDuration(olderString)
older := ctx.Int("older-than")
// Set color.
console.SetColor("Remove", color.New(color.FgGreen, color.Bold))
// Support multiple targets.
for _, url := range ctx.Args() {
prefix := ""
if isPrefix {
if !strings.HasSuffix(url, "/") {
prefix = path.Base(url)
url = path.Dir(url) + "/"
} else if runtime.GOOS == "windows" && !strings.HasSuffix(url, `\`) {
prefix = path.Base(url)
url = path.Dir(url) + `\`
}
}
targetAlias, targetURL, _ := mustExpandAlias(url)
if (isPrefix || isRecursive) && isForce {
rmAll(targetAlias, targetURL, prefix, isRecursive, isIncomplete, isFake, older)
if isRecursive {
removeRecursive(url, isIncomplete, isFake, older)
} else {
if err := rm(targetAlias, targetURL, isIncomplete, isFake, older); err != nil {
errorIf(err.Trace(url), "Unable to remove ‘"+url+"’.")
continue
}
printMsg(rmMessage{Status: "success", URL: url})
removeSingle(url, isIncomplete, isFake, older)
}
}
@@ -324,26 +292,10 @@ func mainRm(ctx *cli.Context) {
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
url := scanner.Text()
prefix := ""
if isPrefix {
if strings.HasSuffix(url, "/") {
prefix = path.Base(url)
url = path.Dir(url)
} else if runtime.GOOS == "windows" && strings.HasSuffix(url, `\`) {
prefix = path.Base(url)
url = path.Dir(url)
}
}
targetAlias, targetURL, _ := mustExpandAlias(url)
if (isPrefix || isRecursive) && isForce {
rmAll(targetAlias, targetURL, prefix, isRecursive, isIncomplete, isFake, older)
if isRecursive {
removeRecursive(url, isIncomplete, isFake, older)
} else {
if err := rm(targetAlias, targetURL, isIncomplete, isFake, older); err != nil {
errorIf(err.Trace(url), "Unable to remove ‘"+url+"’.")
continue
}
printMsg(rmMessage{Status: "success", URL: url})
removeSingle(url, isIncomplete, isFake, older)
}
}
}
+2 -2
View File
@@ -117,8 +117,8 @@ func doShareDownloadURL(targetURL string, isRecursive bool, expiry time.Duration
}
// Generate share URL for each target.
incomplete := false
for content := range clnt.List(isRecursive, incomplete) {
isIncomplete := false
for content := range clnt.List(isRecursive, isIncomplete, DirNone) {
if content.Err != nil {
return content.Err.Trace(clnt.GetURL().String())
}
+122
View File
@@ -17,6 +17,9 @@
package minio
import (
"bytes"
"encoding/xml"
"io"
"net/http"
"net/url"
)
@@ -74,6 +77,125 @@ func (c Client) RemoveObject(bucketName, objectName string) error {
return nil
}
// RemoveObjectError - container of Multi Delete S3 API error
type RemoveObjectError struct {
ObjectName string
Err error
}
// generateRemoveMultiObjects - generate the XML request for remove multi objects request
func generateRemoveMultiObjectsRequest(objects []string) []byte {
rmObjects := []deleteObject{}
for _, obj := range objects {
rmObjects = append(rmObjects, deleteObject{Key: obj})
}
xmlBytes, _ := xml.Marshal(deleteMultiObjects{Objects: rmObjects, Quiet: true})
return xmlBytes
}
// processRemoveMultiObjectsResponse - parse the remove multi objects web service
// and return the success/failure result status for each object
func processRemoveMultiObjectsResponse(body io.Reader, objects []string, errorCh chan<- RemoveObjectError) {
// Parse multi delete XML response
rmResult := &deleteMultiObjectsResult{}
err := xmlDecoder(body, rmResult)
if err != nil {
errorCh <- RemoveObjectError{ObjectName: "", Err: err}
return
}
// Fill deletion that returned an error.
for _, obj := range rmResult.UnDeletedObjects {
errorCh <- RemoveObjectError{
ObjectName: obj.Key,
Err: ErrorResponse{
Code: obj.Code,
Message: obj.Message,
},
}
}
}
// RemoveObjects remove multiples objects from a bucket.
// The list of objects to remove are received from objectsCh.
// Remove failures are sent back via error channel.
func (c Client) RemoveObjects(bucketName string, objectsCh <-chan string) <-chan RemoveObjectError {
errorCh := make(chan RemoveObjectError, 1)
// Validate if bucket name is valid.
if err := isValidBucketName(bucketName); err != nil {
defer close(errorCh)
errorCh <- RemoveObjectError{
Err: err,
}
return errorCh
}
// Validate objects channel to be properly allocated.
if objectsCh == nil {
defer close(errorCh)
errorCh <- RemoveObjectError{
Err: ErrInvalidArgument("Objects channel cannot be nil"),
}
return errorCh
}
// Generate and call MultiDelete S3 requests based on entries received from objectsCh
go func(errorCh chan<- RemoveObjectError) {
maxEntries := 1000
finish := false
urlValues := make(url.Values)
urlValues.Set("delete", "")
// Close error channel when Multi delete finishes.
defer close(errorCh)
// Loop over entries by 1000 and call MultiDelete requests
for {
if finish {
break
}
count := 0
var batch []string
// Try to gather 1000 entries
for object := range objectsCh {
batch = append(batch, object)
if count++; count >= maxEntries {
break
}
}
if count < maxEntries {
// We didn't have 1000 entries, so this is the last batch
finish = true
}
// Generate remove multi objects XML request
removeBytes := generateRemoveMultiObjectsRequest(batch)
// Execute GET on bucket to list objects.
resp, err := c.executeMethod("POST", requestMetadata{
bucketName: bucketName,
queryValues: urlValues,
contentBody: bytes.NewReader(removeBytes),
contentLength: int64(len(removeBytes)),
contentMD5Bytes: sumMD5(removeBytes),
contentSHA256Bytes: sum256(removeBytes),
})
if err != nil {
for _, b := range batch {
errorCh <- RemoveObjectError{ObjectName: b, Err: err}
}
continue
}
// Process multiobjects remove xml response
processRemoveMultiObjectsResponse(resp.Body, batch, errorCh)
closeResponse(resp)
}
}(errorCh)
return errorCh
}
// RemoveIncompleteUpload aborts an partially uploaded object.
// Requires explicit authentication, no anonymous requests are allowed for multipart API.
func (c Client) RemoveIncompleteUpload(bucketName, objectName string) error {
+35
View File
@@ -206,3 +206,38 @@ type createBucketConfiguration struct {
XMLName xml.Name `xml:"http://s3.amazonaws.com/doc/2006-03-01/ CreateBucketConfiguration" json:"-"`
Location string `xml:"LocationConstraint"`
}
// deleteObject container for Delete element in MultiObjects Delete XML request
type deleteObject struct {
Key string
VersionId string `xml:"VersionId,omitempty"`
}
// deletedObject container for Deleted element in MultiObjects Delete XML response
type deletedObject struct {
Key string
VersionId string `xml:"VersionId,omitempty"`
DeleteMarker bool
DeleteMarkerVersionId string
}
// nonDeletedObject container for Error element (failed deletion) in MultiObjects Delete XML response
type nonDeletedObject struct {
Key string
Code string
Message string
}
// deletedMultiObjects container for MultiObjects Delete XML request
type deleteMultiObjects struct {
XMLName xml.Name `xml:"Delete"`
Quiet bool
Objects []deleteObject `xml:"Object"`
}
// deletedMultiObjectsResult container for MultiObjects Delete XML response
type deleteMultiObjectsResult struct {
XMLName xml.Name `xml:"DeleteResult"`
DeletedObjects []deletedObject `xml:"Deleted"`
UnDeletedObjects []nonDeletedObject `xml:"Error"`
}
+1 -1
View File
@@ -73,7 +73,7 @@ type Client struct {
// Global constants.
const (
libraryName = "minio-go"
libraryVersion = "2.0.1"
libraryVersion = "2.0.2"
)
// User Agent should always following the below style.
+3 -3
View File
@@ -49,10 +49,10 @@
"revisionTime": "2015-10-24T22:24:27-07:00"
},
{
"checksumSHA1": "KF1E63M2/GZr/xNzK0VZR3UONhc=",
"checksumSHA1": "vGCh8c5ZOLKaxsVtSbK5Nrf4SOA=",
"path": "github.com/minio/minio-go",
"revision": "ddc4ca3e14e8727280ac7d805a9d97cf00dba314",
"revisionTime": "2016-09-27T20:29:50Z"
"revision": "c040578255dbb1a1f41cbdc5bd944de4140b4149",
"revisionTime": "2016-10-10T18:05:01Z"
},
{
"checksumSHA1": "qTxOBp3GVxCC70ykb7Hxg6UgWwA=",