Implement rewind flag in ls and cp commands (#3304)

--rewind will go back in time and select specific object versions that are
the latest at the specified time.

--versions will display all the versions

cp will just ignore if the latest version is a delete marker
ls will print delete markers with a (deleted) at the end
This commit is contained in:
Anis Elleuch
2020-07-23 11:18:38 -07:00
committed by GitHub
parent a2592cef84
commit 442facedd1
35 changed files with 532 additions and 258 deletions
+1 -1
View File
@@ -221,7 +221,7 @@ func mainAdminHeal(ctx *cli.Context) error {
fatalIf(err.Trace(clnt.GetURL().String()), "Unable to create client for URL ", aliasedURL)
return nil
}
for content := range clnt.List(globalContext, false, false, false, DirNone) {
for content := range clnt.List(globalContext, ListOptions{isRecursive: false, showDir: DirNone}) {
if content.Err != nil {
fatalIf(content.Err.Trace(clnt.GetURL().String()), "Unable to heal bucket `"+bucket+"`.")
return nil
+1 -1
View File
@@ -96,7 +96,7 @@ func completeS3Path(s3Path string) (prediction []string) {
// List dirPath content and only pick elements that corresponds
// to the path that we want to complete
for content := range clnt.List(globalContext, false, false, false, DirFirst) {
for content := range clnt.List(globalContext, ListOptions{isRecursive: false, showDir: DirFirst}) {
cmplS3Path := alias + getKey(content)
if content.Type.IsDir() {
if !strings.HasSuffix(cmplS3Path, "/") {
+2 -1
View File
@@ -25,6 +25,7 @@ import (
"os"
"strings"
"syscall"
"time"
"unicode"
"unicode/utf8"
@@ -153,7 +154,7 @@ func catURL(ctx context.Context, sourceURL string, encKeyDB map[string][]prefixS
// downloaded object is equal to the original one. FS files
// are ignored since some of them have zero size though they
// have contents like files under /proc.
client, content, err := url2Stat(ctx, sourceURL, false, encKeyDB)
client, content, err := url2Stat(ctx, sourceURL, "", false, encKeyDB, time.Time{})
if err == nil && client.GetURL().Type == objectStorage {
size = content.Size
}
+13 -13
View File
@@ -421,7 +421,7 @@ func (f *fsClient) ShareUpload(ctx context.Context, startsWith bool, expires tim
}
// Copy - copy data from source to destination
func (f *fsClient) Copy(ctx context.Context, source string, size int64, progress io.Reader, srcSSE, tgtSSE encrypt.ServerSide, metadata map[string]string, disableMultipart, preserve bool) *probe.Error {
func (f *fsClient) Copy(ctx context.Context, source string, opts CopyOptions, progress io.Reader) *probe.Error {
rc, e := os.Open(source)
if e != nil {
err := f.toClientError(e, source)
@@ -430,14 +430,14 @@ 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, opts.size, opts.metadata, progress, opts.isPreserve); err != nil {
return err.Trace(destination, source)
}
return nil
}
// Get returns reader and any additional metadata.
func (f *fsClient) Get(ctx context.Context, sse encrypt.ServerSide) (io.ReadCloser, *probe.Error) {
func (f *fsClient) Get(ctx context.Context, opts GetOptions) (io.ReadCloser, *probe.Error) {
fileData, e := os.Open(f.PathURL.Path)
if e != nil {
err := f.toClientError(e, f.PathURL.Path)
@@ -530,18 +530,18 @@ func (f *fsClient) Remove(ctx context.Context, isIncomplete, isRemoveBucket, isB
}
// List - list files and folders.
func (f *fsClient) List(ctx context.Context, isRecursive, isIncomplete, isMetadata bool, showDir DirOpt) <-chan *ClientContent {
func (f *fsClient) List(ctx context.Context, opts ListOptions) <-chan *ClientContent {
contentCh := make(chan *ClientContent)
filteredCh := make(chan *ClientContent)
if isRecursive {
if showDir == DirNone {
go f.listRecursiveInRoutine(contentCh, isMetadata)
if opts.isRecursive {
if opts.showDir == DirNone {
go f.listRecursiveInRoutine(contentCh, opts.isFetchMeta)
} else {
go f.listDirOpt(contentCh, isIncomplete, isMetadata, showDir)
go f.listDirOpt(contentCh, opts.isIncomplete, opts.isFetchMeta, opts.showDir)
}
} else {
go f.listInRoutine(contentCh, isMetadata)
go f.listInRoutine(contentCh, opts.isFetchMeta)
}
// This function filters entries from any listing go routine
@@ -549,7 +549,7 @@ func (f *fsClient) List(ctx context.Context, isRecursive, isIncomplete, isMetada
// only show partly uploaded files,
go func() {
for c := range contentCh {
if isIncomplete {
if opts.isIncomplete {
if !strings.HasSuffix(c.URL.Path, partSuffix) {
continue
}
@@ -1014,8 +1014,8 @@ func (f *fsClient) SetAccess(ctx context.Context, access string, isJSON bool) *p
}
// Stat - get metadata from path.
func (f *fsClient) Stat(ctx context.Context, isIncomplete, isPreserve bool, sse encrypt.ServerSide) (content *ClientContent, err *probe.Error) {
st, err := f.fsStat(isIncomplete)
func (f *fsClient) Stat(ctx context.Context, opts StatOptions) (content *ClientContent, err *probe.Error) {
st, err := f.fsStat(opts.incomplete)
if err != nil {
return nil, err.Trace(f.PathURL.String())
}
@@ -1032,7 +1032,7 @@ func (f *fsClient) Stat(ctx context.Context, isIncomplete, isPreserve bool, sse
path := f.PathURL.String()
// Populates meta data with file system attribute only in case of
// when preserve flag is passed.
if isPreserve {
if opts.preserve {
fileAttr, err := disk.GetFileSystemAttrs(path)
if err != nil {
return content, nil
+9 -10
View File
@@ -65,7 +65,7 @@ func (s *TestSuite) TestList(c *C) {
// Verify previously create files and list them.
var contents []*ClientContent
for content := range fsClient.List(globalContext, false, false, false, DirNone) {
for content := range fsClient.List(globalContext, ListOptions{showDir: DirNone}) {
if content.Err != nil {
err = content.Err
break
@@ -93,7 +93,7 @@ func (s *TestSuite) TestList(c *C) {
contents = nil
// List non recursive to list only top level files.
for content := range fsClient.List(globalContext, false, false, false, DirNone) {
for content := range fsClient.List(globalContext, ListOptions{showDir: DirNone}) {
if content.Err != nil {
err = content.Err
break
@@ -109,7 +109,7 @@ func (s *TestSuite) TestList(c *C) {
contents = nil
// List recursively all files and verify.
for content := range fsClient.List(globalContext, true, false, false, DirNone) {
for content := range fsClient.List(globalContext, ListOptions{isRecursive: true, showDir: DirNone}) {
if content.Err != nil {
err = content.Err
break
@@ -153,7 +153,7 @@ func (s *TestSuite) TestList(c *C) {
contents = nil
// List recursively all files and verify.
for content := range fsClient.List(globalContext, true, false, false, DirNone) {
for content := range fsClient.List(globalContext, ListOptions{isRecursive: true, showDir: DirNone}) {
if content.Err != nil {
err = content.Err
break
@@ -210,7 +210,7 @@ func (s *TestSuite) TestStatBucket(c *C) {
c.Assert(err, IsNil)
err = fsClient.MakeBucket(context.Background(), "us-east-1", true, false)
c.Assert(err, IsNil)
_, err = fsClient.Stat(context.Background(), false, false, nil)
_, err = fsClient.Stat(context.Background(), StatOptions{})
c.Assert(err, IsNil)
}
@@ -275,7 +275,7 @@ func (s *TestSuite) TestGet(c *C) {
c.Assert(err, IsNil)
c.Assert(n, Equals, int64(len(data)))
reader, err = fsClient.Get(context.Background(), nil)
reader, err = fsClient.Get(context.Background(), GetOptions{})
c.Assert(err, IsNil)
var results bytes.Buffer
_, e = io.Copy(&results, reader)
@@ -303,7 +303,7 @@ func (s *TestSuite) TestGetRange(c *C) {
c.Assert(err, IsNil)
c.Assert(n, Equals, int64(len(data)))
reader, err = fsClient.Get(context.Background(), nil)
reader, err = fsClient.Get(context.Background(), GetOptions{})
c.Assert(err, IsNil)
var results bytes.Buffer
buf := make([]byte, 5)
@@ -334,7 +334,7 @@ func (s *TestSuite) TestStatObject(c *C) {
c.Assert(err, IsNil)
c.Assert(n, Equals, int64(len(data)))
content, err := fsClient.Stat(context.Background(), false, false, nil)
content, err := fsClient.Stat(context.Background(), StatOptions{})
c.Assert(err, IsNil)
c.Assert(content.Size, Equals, int64(dataLen))
}
@@ -358,7 +358,6 @@ func (s *TestSuite) TestCopy(c *C) {
}, nil, nil, false, false, false)
c.Assert(err, IsNil)
c.Assert(n, Equals, int64(len(data)))
err = fsClientTarget.Copy(context.Background(), sourcePath, int64(len(data)), nil, nil, nil, nil, false, false)
err = fsClientTarget.Copy(context.Background(), sourcePath, CopyOptions{size: int64(len(data))}, nil)
c.Assert(err, IsNil)
}
+139 -45
View File
@@ -809,12 +809,14 @@ func (c *S3Client) Watch(ctx context.Context, options WatchOptions) (*WatchObjec
return wo, nil
}
// Get - get object with metadata.
func (c *S3Client) Get(ctx context.Context, sse encrypt.ServerSide) (io.ReadCloser, *probe.Error) {
// Get - get object with GET options.
func (c *S3Client) Get(ctx context.Context, opts GetOptions) (io.ReadCloser, *probe.Error) {
bucket, object := c.url2BucketAndObject()
opts := minio.GetObjectOptions{}
opts.ServerSideEncryption = sse
reader, e := c.api.GetObject(ctx, bucket, object, opts)
reader, e := c.api.GetObject(ctx, bucket, object,
minio.GetObjectOptions{
ServerSideEncryption: opts.sse,
VersionID: opts.versionID,
})
if e != nil {
errResponse := minio.ToErrorResponse(e)
if errResponse.Code == "NoSuchBucket" {
@@ -838,7 +840,7 @@ func (c *S3Client) Get(ctx context.Context, sse encrypt.ServerSide) (io.ReadClos
// Copy - copy object, uses server side copy API. Also uses an abstracted API
// such that large file sizes will be copied in multipart manner on server
// side.
func (c *S3Client) Copy(ctx context.Context, source string, size int64, progress io.Reader, srcSSE, tgtSSE encrypt.ServerSide, metadata map[string]string, disableMultipart, isPreserve bool) *probe.Error {
func (c *S3Client) Copy(ctx context.Context, source string, opts CopyOptions, progress io.Reader) *probe.Error {
dstBucket, dstObject := c.url2BucketAndObject()
if dstBucket == "" {
return probe.NewError(BucketNameEmpty{})
@@ -850,39 +852,40 @@ func (c *S3Client) Copy(ctx context.Context, source string, size int64, progress
srcOpts := minio.CopySrcOptions{
Bucket: tokens[1],
Object: tokens[2],
Encryption: srcSSE,
Encryption: opts.srcSSE,
VersionID: opts.versionID,
}
destOpts := minio.CopyDestOptions{
Bucket: dstBucket,
Object: dstObject,
Encryption: tgtSSE,
Encryption: opts.tgtSSE,
Progress: progress,
Size: size,
Size: opts.size,
}
if lockModeStr, ok := metadata[AmzObjectLockMode]; ok {
if lockModeStr, ok := opts.metadata[AmzObjectLockMode]; ok {
destOpts.Mode = minio.RetentionMode(strings.ToUpper(lockModeStr))
delete(metadata, AmzObjectLockMode)
delete(opts.metadata, AmzObjectLockMode)
}
if retainUntilDateStr, ok := metadata[AmzObjectLockRetainUntilDate]; ok {
delete(metadata, AmzObjectLockRetainUntilDate)
if retainUntilDateStr, ok := opts.metadata[AmzObjectLockRetainUntilDate]; ok {
delete(opts.metadata, AmzObjectLockRetainUntilDate)
if t, e := time.Parse(time.RFC3339, retainUntilDateStr); e == nil {
destOpts.RetainUntilDate = t.UTC()
}
}
if lh, ok := metadata[AmzObjectLockLegalHold]; ok {
if lh, ok := opts.metadata[AmzObjectLockLegalHold]; ok {
destOpts.LegalHold = minio.LegalHoldStatus(lh)
delete(metadata, AmzObjectLockLegalHold)
delete(opts.metadata, AmzObjectLockLegalHold)
}
// Assign metadata after irrelevant parts are delete above
destOpts.UserMetadata = metadata
destOpts.UserMetadata = opts.metadata
var e error
if disableMultipart || size < 64*1024*1024 {
if opts.disableMultipart || opts.size < 64*1024*1024 {
_, e = c.api.CopyObject(ctx, destOpts, srcOpts)
} else {
_, e = c.api.ComposeObject(ctx, destOpts, srcOpts)
@@ -1314,8 +1317,12 @@ func (c *S3Client) SetAccess(ctx context.Context, bucketPolicy string, isJSON bo
return nil
}
// listObjectWrapper - select ObjectList version depending on the target hostname
func (c *S3Client) listObjectWrapper(ctx context.Context, bucket, object string, isRecursive bool, doneCh chan struct{}, metadata bool) <-chan minio.ObjectInfo {
// listObjectWrapper - select ObjectList mode depending on arguments
func (c *S3Client) listObjectWrapper(ctx context.Context, bucket, object string, isRecursive bool, timeRef time.Time, withVersions, withDeleteMarkers bool, metadata bool) <-chan minio.ObjectInfo {
if !timeRef.IsZero() || withVersions {
return c.listVersions(ctx, bucket, object, isRecursive, timeRef, withVersions, withDeleteMarkers)
}
if isGoogle(c.targetURL.Host) {
// Google Cloud S3 layer doesn't implement ListObjectsV2 implementation
// https://github.com/minio/mc/issues/3073
@@ -1359,7 +1366,7 @@ func (c *S3Client) statIncompleteUpload(ctx context.Context, bucket, object stri
// Stat - send a 'HEAD' on a bucket or object to fetch its metadata. It also returns
// a DIR type content if a prefix does exist in the server.
func (c *S3Client) Stat(ctx context.Context, isIncomplete, isPreserve bool, sse encrypt.ServerSide) (*ClientContent, *probe.Error) {
func (c *S3Client) Stat(ctx context.Context, opts StatOptions) (*ClientContent, *probe.Error) {
c.Lock()
defer c.Unlock()
bucket, object := c.url2BucketAndObject()
@@ -1378,7 +1385,7 @@ func (c *S3Client) Stat(ctx context.Context, isIncomplete, isPreserve bool, sse
}
// If the request is for incomplete upload stat, handle it here.
if isIncomplete {
if opts.incomplete {
return c.statIncompleteUpload(ctx, bucket, object)
}
@@ -1390,13 +1397,14 @@ func (c *S3Client) Stat(ctx context.Context, isIncomplete, isPreserve bool, sse
// - /path/to/empty_directory
// - /path/to/empty_directory/
opts := minio.StatObjectOptions{}
opts.ServerSideEncryption = sse
if !strings.HasSuffix(object, string(c.targetURL.Separator)) {
// First an HEAD call is issued, this is faster than doing listing even if the object exists
// because the list could be very large. At the same time, the HEAD call is avoided if the
// object already contains a trailing prefix or we passed rewind flag to know the object version
// created just before the rewind parameter.
if !strings.HasSuffix(object, string(c.targetURL.Separator)) && opts.timeRef.IsZero() {
// Issue HEAD request first but ignore no such key error
// so we can check if there is such prefix which exists
ctnt, err := c.getObjectStat(ctx, bucket, object, opts)
ctnt, err := c.getObjectStat(ctx, bucket, object, minio.StatObjectOptions{ServerSideEncryption: opts.sse, VersionID: opts.versionID})
if err == nil {
return ctnt, err
}
@@ -1412,10 +1420,15 @@ func (c *S3Client) Stat(ctx context.Context, isIncomplete, isPreserve bool, sse
// Prefix to pass to minio-go listing in order to fetch if a prefix exists
prefix := strings.TrimRight(object, string(c.targetURL.Separator))
for objectStat := range c.listObjectWrapper(ctx, bucket, prefix, nonRecursive, nil, false) {
for objectStat := range c.listObjectWrapper(ctx, bucket, prefix, nonRecursive, opts.timeRef, false, false, false) {
if objectStat.Err != nil {
return nil, probe.NewError(objectStat.Err)
}
if objectStat.Key == prefix {
return c.objectInfo2ClientContent(bucket, objectStat), nil
}
if strings.HasSuffix(objectStat.Key, string(c.targetURL.Separator)) {
objectMetadata.URL = c.targetURL.Clone()
objectMetadata.Type = os.ModeDir
@@ -1541,31 +1554,110 @@ func (c *S3Client) splitPath(path string) (bucketName, objectName string) {
/// Bucket API operations.
func (c *S3Client) snapshot(ctx context.Context, isRecursive bool, timeRef time.Time, includeOlderVersions, withDeleteMarkers bool) <-chan *ClientContent {
bucket, object := c.url2BucketAndObject()
contentCh := make(chan *ClientContent)
go func() {
defer close(contentCh)
for objectVersion := range c.listVersions(ctx, bucket, object, isRecursive, timeRef, includeOlderVersions, withDeleteMarkers) {
contentCh <- c.objectInfo2ClientContent(bucket, objectVersion)
}
}()
return contentCh
}
func (c *S3Client) listVersions(ctx context.Context, b, o string, isRecursive bool, timeRef time.Time, includeOlderVersions, withDeleteMarkers bool) chan minio.ObjectInfo {
objectInfoCh := make(chan minio.ObjectInfo)
go func() {
defer close(objectInfoCh)
c.listVersionsRoutine(ctx, b, o, isRecursive, timeRef, includeOlderVersions, withDeleteMarkers, objectInfoCh)
}()
return objectInfoCh
}
func (c *S3Client) listVersionsRoutine(ctx context.Context, b, o string, isRecursive bool, timeRef time.Time, includeOlderVersions, withDeleteMarkers bool, objectInfoCh chan minio.ObjectInfo) {
if timeRef.IsZero() {
timeRef = time.Now().UTC()
}
var buckets []string
if b == "" {
bucketsInfo, err := c.api.ListBuckets(ctx)
if err != nil {
objectInfoCh <- minio.ObjectInfo{
Err: err,
}
return
}
for _, b := range bucketsInfo {
buckets = append(buckets, b.Name)
}
} else {
buckets = append(buckets, b)
}
for _, b := range buckets {
var skipKey string
for objectVersion := range c.api.ListObjects(ctx, b, minio.ListObjectsOptions{
Prefix: o,
Recursive: isRecursive,
WithVersions: true,
}) {
if objectVersion.Err != nil {
objectInfoCh <- objectVersion
return
}
if !includeOlderVersions && skipKey == objectVersion.Key {
// Skip current version if not are asked to list all versions
// and we already listed the current object key name
continue
}
if objectVersion.LastModified.Before(timeRef) {
skipKey = objectVersion.Key
// Skip if this is a delete marker and we are not asked to list it
if !withDeleteMarkers && objectVersion.IsDeleteMarker {
continue
}
objectInfoCh <- objectVersion
}
}
}
}
// List - list at delimited path, if not recursive.
func (c *S3Client) List(ctx context.Context, isRecursive, isIncomplete, isMetadata bool, showDir DirOpt) <-chan *ClientContent {
func (c *S3Client) List(ctx context.Context, opts ListOptions) <-chan *ClientContent {
c.Lock()
defer c.Unlock()
contentCh := make(chan *ClientContent)
if isIncomplete {
if isRecursive {
if showDir == DirNone {
if !opts.timeRef.IsZero() || opts.withOlderVersions {
return c.snapshot(ctx, opts.isRecursive, opts.timeRef, opts.withOlderVersions, opts.withDeleteMarkers)
}
if opts.isIncomplete {
if opts.isRecursive {
if opts.showDir == DirNone {
go c.listIncompleteRecursiveInRoutine(ctx, contentCh)
} else {
go c.listIncompleteRecursiveInRoutineDirOpt(ctx, contentCh, showDir)
go c.listIncompleteRecursiveInRoutineDirOpt(ctx, contentCh, opts.showDir)
}
} else {
go c.listIncompleteInRoutine(ctx, contentCh)
}
} else {
if isRecursive {
if showDir == DirNone {
go c.listRecursiveInRoutine(ctx, contentCh, isMetadata)
if opts.isRecursive {
if opts.showDir == DirNone {
go c.listRecursiveInRoutine(ctx, contentCh, opts.isFetchMeta)
} else {
go c.listRecursiveInRoutineDirOpt(ctx, contentCh, showDir, isMetadata)
go c.listRecursiveInRoutineDirOpt(ctx, contentCh, opts.showDir, opts.isFetchMeta)
}
} else {
go c.listInRoutine(ctx, contentCh, isMetadata)
go c.listInRoutine(ctx, contentCh, opts.isFetchMeta)
}
}
@@ -1784,8 +1876,7 @@ func (c *S3Client) listIncompleteRecursiveInRoutineDirOpt(ctx context.Context, c
buckets = append(buckets, minio.BucketInfo{Name: bucket, CreationDate: content.Time})
} else if strings.HasSuffix(object, string(c.targetURL.Separator)) {
// Get stat of given object is a directory.
isIncomplete := true
content, perr := c.Stat(ctx, isIncomplete, false, nil)
content, perr := c.Stat(ctx, StatOptions{incomplete: true})
cContent = content
if perr != nil {
contentCh <- &ClientContent{Err: perr.Trace(bucket)}
@@ -1847,6 +1938,10 @@ func (c *S3Client) objectInfo2ClientContent(bucket string, entry minio.ObjectInf
content.ETag = entry.ETag
content.Time = entry.LastModified
content.Expires = entry.Expires
content.VersionID = entry.VersionID
content.StorageClass = entry.StorageClass
content.IsDeleteMarker = entry.IsDeleteMarker
content.IsLatest = entry.IsLatest
content.Metadata = map[string]string{}
content.UserMetadata = map[string]string{}
for k, v := range entry.UserMetadata {
@@ -1885,7 +1980,7 @@ func (c *S3Client) listRecursiveInRoutineDirOpt(ctx context.Context, contentCh c
var listDir func(bucket, object string) bool
listDir = func(bucket, object string) (isStop bool) {
isRecursive := false
for entry := range c.listObjectWrapper(ctx, bucket, object, isRecursive, nil, metadata) {
for entry := range c.listObjectWrapper(ctx, bucket, object, isRecursive, time.Time{}, false, false, metadata) {
if entry.Err != nil {
url := c.targetURL.Clone()
url.Path = c.joinPath(bucket, object)
@@ -1942,8 +2037,7 @@ func (c *S3Client) listRecursiveInRoutineDirOpt(ctx context.Context, contentCh c
buckets = append(buckets, minio.BucketInfo{Name: bucket, CreationDate: content.Time})
} else {
// Get stat of given object is a directory.
isIncomplete := false
content, perr := c.Stat(ctx, isIncomplete, false, nil)
content, perr := c.Stat(ctx, StatOptions{})
cContent = content
if perr != nil {
contentCh <- &ClientContent{Err: perr.Trace(bucket)}
@@ -1993,7 +2087,7 @@ func (c *S3Client) listInRoutine(ctx context.Context, contentCh chan *ClientCont
contentCh <- content
default:
isRecursive := false
for object := range c.listObjectWrapper(ctx, b, o, isRecursive, nil, metadata) {
for object := range c.listObjectWrapper(ctx, b, o, isRecursive, time.Time{}, false, false, metadata) {
if object.Err != nil {
contentCh <- &ClientContent{
Err: probe.NewError(object.Err),
@@ -2039,7 +2133,7 @@ func (c *S3Client) listRecursiveInRoutine(ctx context.Context, contentCh chan *C
}
for _, bucket := range buckets {
isRecursive := true
for object := range c.listObjectWrapper(ctx, bucket.Name, o, isRecursive, nil, metadata) {
for object := range c.listObjectWrapper(ctx, bucket.Name, o, isRecursive, time.Time{}, false, false, metadata) {
if object.Err != nil {
contentCh <- &ClientContent{
Err: probe.NewError(object.Err),
@@ -2051,7 +2145,7 @@ func (c *S3Client) listRecursiveInRoutine(ctx context.Context, contentCh chan *C
}
default:
isRecursive := true
for object := range c.listObjectWrapper(ctx, b, o, isRecursive, nil, metadata) {
for object := range c.listObjectWrapper(ctx, b, o, isRecursive, time.Time{}, false, false, metadata) {
if object.Err != nil {
contentCh <- &ClientContent{
Err: probe.NewError(object.Err),
+4 -4
View File
@@ -178,7 +178,7 @@ func (s *TestSuite) TestBucketOperations(c *C) {
s3c, err = S3New(conf)
c.Assert(err, IsNil)
for content := range s3c.List(globalContext, false, false, false, DirNone) {
for content := range s3c.List(globalContext, ListOptions{showDir: DirNone}) {
c.Assert(content.Err, IsNil)
c.Assert(content.Type.IsDir(), Equals, true)
}
@@ -187,7 +187,7 @@ func (s *TestSuite) TestBucketOperations(c *C) {
s3c, err = S3New(conf)
c.Assert(err, IsNil)
for content := range s3c.List(globalContext, false, false, false, DirNone) {
for content := range s3c.List(globalContext, ListOptions{showDir: DirNone}) {
c.Assert(content.Err, IsNil)
c.Assert(content.Type.IsDir(), Equals, true)
}
@@ -196,7 +196,7 @@ func (s *TestSuite) TestBucketOperations(c *C) {
s3c, err = S3New(conf)
c.Assert(err, IsNil)
for content := range s3c.List(globalContext, false, false, false, DirNone) {
for content := range s3c.List(globalContext, ListOptions{showDir: DirNone}) {
c.Assert(content.Err, IsNil)
c.Assert(content.Type.IsRegular(), Equals, true)
}
@@ -227,7 +227,7 @@ func (s *TestSuite) TestObjectOperations(c *C) {
c.Assert(err, IsNil)
c.Assert(n, Equals, int64(len(object.data)))
reader, err = s3c.Get(context.Background(), nil)
reader, err = s3c.Get(context.Background(), GetOptions{})
c.Assert(err, IsNil)
var buffer bytes.Buffer
{
+4 -6
View File
@@ -23,6 +23,7 @@ import (
"regexp"
"runtime"
"strings"
"time"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/mimedb"
@@ -184,7 +185,7 @@ func urlJoinPath(url1, url2 string) string {
}
// url2Stat returns stat info for URL.
func url2Stat(ctx context.Context, urlStr string, fileAttr bool, encKeyDB map[string][]prefixSSEPair) (client Client, content *ClientContent, err *probe.Error) {
func url2Stat(ctx context.Context, urlStr, versionID string, fileAttr bool, encKeyDB map[string][]prefixSSEPair, timeRef time.Time) (client Client, content *ClientContent, err *probe.Error) {
client, err = newClient(urlStr)
if err != nil {
return nil, nil, err.Trace(urlStr)
@@ -192,7 +193,7 @@ func url2Stat(ctx context.Context, urlStr string, fileAttr bool, encKeyDB map[st
alias, _ := url2Alias(urlStr)
sse := getSSE(urlStr, encKeyDB[alias])
content, err = client.Stat(ctx, false, fileAttr, sse)
content, err = client.Stat(ctx, StatOptions{preserve: fileAttr, sse: sse, timeRef: timeRef, versionID: versionID})
if err != nil {
return nil, nil, err.Trace(urlStr)
}
@@ -229,10 +230,7 @@ func isURLPrefixExists(urlPrefix string, incomplete bool) bool {
if err != nil {
return false
}
isRecursive := false
isIncomplete := incomplete
isFetchMeta := false
for entry := range clnt.List(globalContext, isRecursive, isIncomplete, isFetchMeta, DirNone) {
for entry := range clnt.List(globalContext, ListOptions{isRecursive: false, isIncomplete: incomplete, isFetchMeta: false, showDir: DirNone}) {
return entry.Err == nil
}
return false
+45 -4
View File
@@ -43,11 +43,48 @@ const (
// Default number of multipart workers for a Put operation.
const defaultMultipartThreadsNum = 4
// GetOptions holds options of the GET operation
type GetOptions struct {
sse encrypt.ServerSide
versionID string
}
// StatOptions holds options of the HEAD operation
type StatOptions struct {
incomplete bool
preserve bool
sse encrypt.ServerSide
timeRef time.Time
versionID string
}
// ListOptions holds options for listing operation
type ListOptions struct {
isRecursive bool
isIncomplete bool
isFetchMeta bool
withOlderVersions bool
withDeleteMarkers bool
timeRef time.Time
showDir DirOpt
}
// CopyOptions holds options for copying operation
type CopyOptions struct {
versionID string
size int64
srcSSE, tgtSSE encrypt.ServerSide
metadata map[string]string
disableMultipart bool
isPreserve bool
}
// Client - client interface
type Client interface {
// Common operations
Stat(ctx context.Context, isIncomplete, isPreserve bool, sse encrypt.ServerSide) (content *ClientContent, err *probe.Error)
List(ctx context.Context, isRecursive, isIncomplete, isFetchMeta bool, showDir DirOpt) <-chan *ClientContent
Stat(ctx context.Context, opts StatOptions) (content *ClientContent, err *probe.Error)
List(ctx context.Context, opts ListOptions) <-chan *ClientContent
// Bucket operations
MakeBucket(ctx context.Context, region string, ignoreExisting, withLock bool) *probe.Error
@@ -61,13 +98,14 @@ type Client interface {
SetAccess(ctx context.Context, access string, isJSON bool) *probe.Error
// I/O operations
Copy(ctx context.Context, source string, size int64, progress io.Reader, srcSSE, tgtSSE encrypt.ServerSide, metadata map[string]string, disableMultipart, isPreserve bool) *probe.Error
Copy(ctx context.Context, source string, opts CopyOptions, progress io.Reader) *probe.Error
// Runs select expression on object storage on specific files.
Select(ctx context.Context, expression string, sse encrypt.ServerSide, opts SelectObjectOpts) (io.ReadCloser, *probe.Error)
// I/O operations with metadata.
Get(ctx context.Context, sse encrypt.ServerSide) (reader io.ReadCloser, err *probe.Error)
Get(ctx context.Context, opts GetOptions) (reader io.ReadCloser, err *probe.Error)
Put(ctx context.Context, reader io.Reader, size int64, metadata map[string]string, progress io.Reader, sse encrypt.ServerSide, md5, disableMultipart, isPreserve bool) (n int64, err *probe.Error)
// Object Locking related API
@@ -119,6 +157,9 @@ type ClientContent struct {
BypassGovernance bool
LegalHoldEnabled bool
LegalHold string
VersionID string
IsDeleteMarker bool
IsLatest bool
Err *probe.Error
}
+21 -12
View File
@@ -104,10 +104,10 @@ func getEncKeys(ctx *cli.Context) (map[string][]prefixSSEPair, *probe.Error) {
// Check if the passed URL represents a folder. It may or may not exist yet.
// If it exists, we can easily check if it is a folder, if it doesn't exist,
// we can guess if the url is a folder from how it looks.
func isAliasURLDir(ctx context.Context, aliasURL string, keys map[string][]prefixSSEPair) bool {
func isAliasURLDir(ctx context.Context, aliasURL string, keys map[string][]prefixSSEPair, timeRef time.Time) bool {
// If the target url exists, check if it is a directory
// and return immediately.
_, targetContent, err := url2Stat(ctx, aliasURL, false, keys)
_, targetContent, err := url2Stat(ctx, aliasURL, "", false, keys, timeRef)
if err == nil {
return targetContent.Type.IsDir()
}
@@ -148,7 +148,7 @@ func getSourceStreamMetadataFromURL(ctx context.Context, urlStr string, encKeyDB
return nil, nil, err.Trace(urlStr)
}
sseKey := getSSE(urlStr, encKeyDB[alias])
return getSourceStream(ctx, alias, urlStrFull, true, sseKey, false)
return getSourceStream(ctx, alias, urlStrFull, "", true, sseKey, false)
}
// getSourceStreamFromURL gets a reader from URL.
@@ -158,7 +158,7 @@ func getSourceStreamFromURL(ctx context.Context, urlStr string, encKeyDB map[str
return nil, err.Trace(urlStr)
}
sse := getSSE(urlStr, encKeyDB[alias])
reader, _, err = getSourceStream(ctx, alias, urlStrFull, false, sse, false)
reader, _, err = getSourceStream(ctx, alias, urlStrFull, "", false, sse, false)
return reader, err
}
@@ -210,12 +210,12 @@ func isReadAt(reader io.Reader) (ok bool) {
}
// getSourceStream gets a reader from URL.
func getSourceStream(ctx context.Context, alias string, urlStr string, fetchStat bool, sse encrypt.ServerSide, preserve bool) (reader io.ReadCloser, metadata map[string]string, err *probe.Error) {
func getSourceStream(ctx context.Context, alias, urlStr, versionID string, fetchStat bool, sse encrypt.ServerSide, preserve bool) (reader io.ReadCloser, metadata map[string]string, err *probe.Error) {
sourceClnt, err := newClientFromAlias(alias, urlStr)
if err != nil {
return nil, nil, err.Trace(alias, urlStr)
}
reader, err = sourceClnt.Get(ctx, sse)
reader, err = sourceClnt.Get(ctx, GetOptions{sse: sse, versionID: versionID})
if err != nil {
return nil, nil, err.Trace(alias, urlStr)
}
@@ -241,7 +241,7 @@ func getSourceStream(ctx context.Context, alias string, urlStr string, fetchStat
}
st.ETag = oinfo.ETag
} else {
st, err = sourceClnt.Stat(ctx, false, preserve, sse)
st, err = sourceClnt.Stat(ctx, StatOptions{preserve: preserve, sse: sse})
if err != nil {
return nil, nil, err.Trace(alias, urlStr)
}
@@ -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, sourceVersionID, mode, until, legalHold string, size int64, progress io.Reader, srcSSE, tgtSSE encrypt.ServerSide, metadata map[string]string, disableMultipart, preserve bool) *probe.Error {
targetClnt, err := newClientFromAlias(alias, urlStr)
if err != nil {
@@ -344,8 +344,16 @@ 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)
opts := CopyOptions{
versionID: sourceVersionID,
size: size,
srcSSE: srcSSE, tgtSSE: tgtSSE,
metadata: metadata,
disableMultipart: disableMultipart,
isPreserve: preserve}
err = targetClnt.Copy(ctx, source, opts, progress)
if err != nil {
return err.Trace(alias, urlStr)
}
@@ -376,7 +384,7 @@ func getAllMetadata(ctx context.Context, sourceAlias, sourceURLStr string, srcSS
return nil, err.Trace(sourceAlias, sourceURLStr)
}
st, err := sourceClnt.Stat(ctx, false, true, srcSSE)
st, err := sourceClnt.Stat(ctx, StatOptions{preserve: true, sse: srcSSE})
if err != nil {
return nil, err.Trace(sourceAlias, sourceURLStr)
}
@@ -398,6 +406,7 @@ func getAllMetadata(ctx context.Context, sourceAlias, sourceURLStr string, srcSS
func uploadSourceToTargetURL(ctx context.Context, urls URLs, progress io.Reader, encKeyDB map[string][]prefixSSEPair, preserve bool) URLs {
sourceAlias := urls.SourceAlias
sourceURL := urls.SourceContent.URL
sourceVersion := urls.SourceContent.VersionID
targetAlias := urls.TargetAlias
targetURL := urls.TargetContent.URL
length := urls.SourceContent.Size
@@ -481,7 +490,7 @@ func uploadSourceToTargetURL(ctx context.Context, urls URLs, progress io.Reader,
return urls.WithError(err.Trace(sourceURL.String()))
}
err = copySourceToTargetURL(ctx, targetAlias, targetURL.String(), sourcePath, mode, until,
err = copySourceToTargetURL(ctx, targetAlias, targetURL.String(), sourcePath, sourceVersion, mode, until,
legalHold, length, progress, srcSSE, tgtSSE, filterMetadata(metadata), urls.DisableMultipart, preserve)
} else {
if urls.SourceContent.RetentionEnabled {
@@ -512,7 +521,7 @@ func uploadSourceToTargetURL(ctx context.Context, urls URLs, progress io.Reader,
var reader io.ReadCloser
// Proceed with regular stream copy.
reader, metadata, err = getSourceStream(ctx, sourceAlias, sourceURL.String(), true, srcSSE, preserve)
reader, metadata, err = getSourceStream(ctx, sourceAlias, sourceURL.String(), sourceVersion, true, srcSSE, preserve)
if err != nil {
return urls.WithError(err.Trace(sourceURL.String()))
}
+1 -1
View File
@@ -179,7 +179,7 @@ func probeS3Signature(ctx context.Context, accessKey, secretKey, url string) (st
return "", err
}
if _, err := s3Client.Stat(ctx, false, false, nil); err != nil {
if _, err := s3Client.Stat(ctx, StatOptions{}); err != nil {
e := err.ToGoError()
if _, ok := e.(BucketDoesNotExist); ok {
// Bucket doesn't exist, means signature probing worked successfully.
+15 -4
View File
@@ -1,5 +1,5 @@
/*
* MinIO Client (C) 2014-2019 MinIO, Inc.
* MinIO Client (C) 2014-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.
@@ -37,6 +37,10 @@ import (
// cp command flags.
var (
cpFlags = []cli.Flag{
cli.StringFlag{
Name: "rewind",
Usage: "Move back in time",
},
cli.BoolFlag{
Name: "recursive, r",
Usage: "copy recursively",
@@ -174,6 +178,10 @@ EXAMPLES:
18. Copy a text file to an object storage and disable multipart upload feature.
{{.Prompt}} {{.HelpName}} --disable-multipart myobject.txt play/mybucket
19. Pick versions while copying objects at a specific date/time in the past if the bucket versioning is enabled.
{{.Prompt}} {{.HelpName}} --rewind 10d myobject.txt play/mybucket
`,
}
@@ -273,7 +281,7 @@ func doPrepareCopyURLs(ctx context.Context, session *sessionV8, cancelCopy conte
// Access recursive flag inside the session header.
isRecursive := session.Header.CommandBoolFlags["recursive"]
rewind := session.Header.CommandStringFlags["rewind"]
olderThan := session.Header.CommandStringFlags["older-than"]
newerThan := session.Header.CommandStringFlags["newer-than"]
encryptKeys := session.Header.CommandStringFlags["encrypt-key"]
@@ -289,7 +297,7 @@ func doPrepareCopyURLs(ctx context.Context, session *sessionV8, cancelCopy conte
scanBar = scanBarFactory()
}
URLsCh := prepareCopyURLs(ctx, sourceURLs, targetURL, isRecursive, encKeyDB, olderThan, newerThan)
URLsCh := prepareCopyURLs(ctx, sourceURLs, targetURL, isRecursive, encKeyDB, olderThan, newerThan, parseRewindFlag(rewind))
done := false
for !done {
select {
@@ -397,11 +405,12 @@ func doCopySession(ctx context.Context, cancelCopy context.CancelFunc, cli *cli.
isRecursive := cli.Bool("recursive")
olderThan := cli.String("older-than")
newerThan := cli.String("newer-than")
rewind := cli.String("rewind")
go func() {
totalBytes := int64(0)
for cpURLs := range prepareCopyURLs(ctx, sourceURLs, targetURL, isRecursive,
encKeyDB, olderThan, newerThan) {
encKeyDB, olderThan, newerThan, parseRewindFlag(rewind)) {
if cpURLs.Error != nil {
// Print in new line and adjust to top so that we
// don't print over the ongoing scan bar
@@ -733,6 +742,7 @@ func mainCopy(cliCtx *cli.Context) error {
console.SetColor("Copy", color.New(color.FgGreen, color.Bold))
recursive := cliCtx.Bool("recursive")
rewind := cliCtx.String("rewind")
olderThan := cliCtx.String("older-than")
newerThan := cliCtx.String("newer-than")
storageClass := cliCtx.String("storage-class")
@@ -761,6 +771,7 @@ func mainCopy(cliCtx *cli.Context) error {
session = newSessionV8(sessionID)
session.Header.CommandType = "cp"
session.Header.CommandBoolFlags["recursive"] = recursive
session.Header.CommandStringFlags["rewind"] = rewind
session.Header.CommandStringFlags["older-than"] = olderThan
session.Header.CommandStringFlags["newer-than"] = newerThan
session.Header.CommandStringFlags["storage-class"] = storageClass
+19 -16
View File
@@ -20,6 +20,7 @@ import (
"context"
"fmt"
"runtime"
"time"
"github.com/minio/cli"
"github.com/minio/minio/pkg/console"
@@ -42,10 +43,12 @@ func checkCopySyntax(ctx context.Context, cliCtx *cli.Context, encKeyDB map[stri
srcURLs := URLs[:len(URLs)-1]
tgtURL := URLs[len(URLs)-1]
isRecursive := cliCtx.Bool("recursive")
rewind := cliCtx.String("rewind")
timeRef := parseRewindFlag(rewind)
// Verify if source(s) exists.
for _, srcURL := range srcURLs {
_, _, err := url2Stat(ctx, srcURL, false, encKeyDB)
_, _, err := url2Stat(ctx, srcURL, "", false, encKeyDB, timeRef)
if err != nil {
console.Fatalf("Unable to validate source %s\n", srcURL)
}
@@ -73,20 +76,20 @@ func checkCopySyntax(ctx context.Context, cliCtx *cli.Context, encKeyDB map[stri
}
// Guess CopyURLsType based on source and target URLs.
copyURLsType, err := guessCopyURLType(ctx, srcURLs, tgtURL, isRecursive, encKeyDB)
copyURLsType, _, err := guessCopyURLType(ctx, srcURLs, tgtURL, isRecursive, encKeyDB, timeRef)
if err != nil {
fatalIf(errInvalidArgument().Trace(), "Unable to guess the type of "+operation+" operation.")
}
switch copyURLsType {
case copyURLsTypeA: // File -> File.
checkCopySyntaxTypeA(ctx, srcURLs, tgtURL, encKeyDB, isMvCmd)
checkCopySyntaxTypeA(ctx, srcURLs, tgtURL, encKeyDB, isMvCmd, timeRef)
case copyURLsTypeB: // File -> Folder.
checkCopySyntaxTypeB(ctx, srcURLs, tgtURL, encKeyDB, isMvCmd)
checkCopySyntaxTypeB(ctx, srcURLs, tgtURL, encKeyDB, isMvCmd, timeRef)
case copyURLsTypeC: // Folder... -> Folder.
checkCopySyntaxTypeC(ctx, srcURLs, tgtURL, isRecursive, encKeyDB, isMvCmd)
checkCopySyntaxTypeC(ctx, srcURLs, tgtURL, isRecursive, encKeyDB, isMvCmd, timeRef)
case copyURLsTypeD: // File1...FileN -> Folder.
checkCopySyntaxTypeD(ctx, srcURLs, tgtURL, encKeyDB, isMvCmd)
checkCopySyntaxTypeD(ctx, srcURLs, tgtURL, encKeyDB, isMvCmd, timeRef)
default:
fatalIf(errInvalidArgument().Trace(), "Unable to guess the type of "+operation+" operation.")
}
@@ -98,13 +101,13 @@ func checkCopySyntax(ctx context.Context, cliCtx *cli.Context, encKeyDB map[stri
}
// checkCopySyntaxTypeA verifies if the source and target are valid file arguments.
func checkCopySyntaxTypeA(ctx context.Context, srcURLs []string, tgtURL string, keys map[string][]prefixSSEPair, isMvCmd bool) {
func checkCopySyntaxTypeA(ctx context.Context, srcURLs []string, tgtURL string, keys map[string][]prefixSSEPair, isMvCmd bool, timeRef time.Time) {
// Check source.
if len(srcURLs) != 1 {
fatalIf(errInvalidArgument().Trace(), "Invalid number of source arguments.")
}
srcURL := srcURLs[0]
_, srcContent, err := url2Stat(ctx, srcURL, false, keys)
_, srcContent, err := url2Stat(ctx, srcURL, "", false, keys, timeRef)
fatalIf(err.Trace(srcURL), "Unable to stat source `"+srcURL+"`.")
if !srcContent.Type.IsRegular() {
@@ -113,13 +116,13 @@ func checkCopySyntaxTypeA(ctx context.Context, srcURLs []string, tgtURL string,
}
// checkCopySyntaxTypeB verifies if the source is a valid file and target is a valid folder.
func checkCopySyntaxTypeB(ctx context.Context, srcURLs []string, tgtURL string, keys map[string][]prefixSSEPair, isMvCmd bool) {
func checkCopySyntaxTypeB(ctx context.Context, srcURLs []string, tgtURL string, keys map[string][]prefixSSEPair, isMvCmd bool, timeRef time.Time) {
// Check source.
if len(srcURLs) != 1 {
fatalIf(errInvalidArgument().Trace(), "Invalid number of source arguments.")
}
srcURL := srcURLs[0]
_, srcContent, err := url2Stat(ctx, srcURL, false, keys)
_, srcContent, err := url2Stat(ctx, srcURL, "", false, keys, timeRef)
fatalIf(err.Trace(srcURL), "Unable to stat source `"+srcURL+"`.")
if !srcContent.Type.IsRegular() {
@@ -127,7 +130,7 @@ func checkCopySyntaxTypeB(ctx context.Context, srcURLs []string, tgtURL string,
}
// Check target.
if _, tgtContent, err := url2Stat(ctx, tgtURL, false, keys); err == nil {
if _, tgtContent, err := url2Stat(ctx, tgtURL, "", false, keys, timeRef); err == nil {
if !tgtContent.Type.IsDir() {
fatalIf(errInvalidArgument().Trace(tgtURL), "Target `"+tgtURL+"` is not a folder.")
}
@@ -135,21 +138,21 @@ func checkCopySyntaxTypeB(ctx context.Context, srcURLs []string, tgtURL string,
}
// checkCopySyntaxTypeC verifies if the source is a valid recursive dir and target is a valid folder.
func checkCopySyntaxTypeC(ctx context.Context, srcURLs []string, tgtURL string, isRecursive bool, keys map[string][]prefixSSEPair, isMvCmd bool) {
func checkCopySyntaxTypeC(ctx context.Context, srcURLs []string, tgtURL string, isRecursive bool, keys map[string][]prefixSSEPair, isMvCmd bool, timeRef time.Time) {
// Check source.
if len(srcURLs) != 1 {
fatalIf(errInvalidArgument().Trace(), "Invalid number of source arguments.")
}
// Check target.
if _, tgtContent, err := url2Stat(ctx, tgtURL, false, keys); err == nil {
if _, tgtContent, err := url2Stat(ctx, tgtURL, "", false, keys, timeRef); err == nil {
if !tgtContent.Type.IsDir() {
fatalIf(errInvalidArgument().Trace(tgtURL), "Target `"+tgtURL+"` is not a folder.")
}
}
for _, srcURL := range srcURLs {
c, srcContent, err := url2Stat(ctx, srcURL, false, keys)
c, srcContent, err := url2Stat(ctx, srcURL, "", false, keys, timeRef)
// incomplete uploads are not necessary for copy operation, no need to verify for them.
isIncomplete := false
if err != nil {
@@ -184,10 +187,10 @@ func checkCopySyntaxTypeC(ctx context.Context, srcURLs []string, tgtURL string,
}
// checkCopySyntaxTypeD verifies if the source is a valid list of files and target is a valid folder.
func checkCopySyntaxTypeD(ctx context.Context, srcURLs []string, tgtURL string, keys map[string][]prefixSSEPair, isMvCmd bool) {
func checkCopySyntaxTypeD(ctx context.Context, srcURLs []string, tgtURL string, keys map[string][]prefixSSEPair, isMvCmd bool, timeRef time.Time) {
// Source can be anything: file, dir, dir...
// Check target if it is a dir
if _, tgtContent, err := url2Stat(ctx, tgtURL, false, keys); err == nil {
if _, tgtContent, err := url2Stat(ctx, tgtURL, "", false, keys, timeRef); err == nil {
if !tgtContent.Type.IsDir() {
fatalIf(errInvalidArgument().Trace(tgtURL), "Target `"+tgtURL+"` is not a folder.")
}
+27 -27
View File
@@ -20,6 +20,7 @@ import (
"context"
"path/filepath"
"strings"
"time"
"github.com/minio/mc/pkg/probe"
)
@@ -51,45 +52,45 @@ const (
// guessCopyURLType guesses the type of clientURL. This approach all allows prepareURL
// functions to accurately report failure causes.
func guessCopyURLType(ctx context.Context, sourceURLs []string, targetURL string, isRecursive bool, keys map[string][]prefixSSEPair) (copyURLsType, *probe.Error) {
func guessCopyURLType(ctx context.Context, sourceURLs []string, targetURL string, isRecursive bool, keys map[string][]prefixSSEPair, timeRef time.Time) (copyURLsType, string, *probe.Error) {
if len(sourceURLs) == 1 { // 1 Source, 1 Target
sourceURL := sourceURLs[0]
_, sourceContent, err := url2Stat(ctx, sourceURL, false, keys)
_, sourceContent, err := url2Stat(ctx, sourceURL, "", false, keys, timeRef)
if err != nil {
return copyURLsTypeInvalid, err
return copyURLsTypeInvalid, "", err
}
// If recursion is ON, it is type C.
// If source is a folder, it is Type C.
if sourceContent.Type.IsDir() || isRecursive {
return copyURLsTypeC, nil
return copyURLsTypeC, "", nil
}
// If target is a folder, it is Type B.
if isAliasURLDir(ctx, targetURL, keys) {
return copyURLsTypeB, nil
if isAliasURLDir(ctx, targetURL, keys, timeRef) {
return copyURLsTypeB, sourceContent.VersionID, nil
}
// else Type A.
return copyURLsTypeA, nil
return copyURLsTypeA, sourceContent.VersionID, nil
}
// Multiple source args and target is a folder. It is Type D.
if isAliasURLDir(ctx, targetURL, keys) {
return copyURLsTypeD, nil
if isAliasURLDir(ctx, targetURL, keys, timeRef) {
return copyURLsTypeD, "", nil
}
return copyURLsTypeInvalid, errInvalidArgument().Trace()
return copyURLsTypeInvalid, "", errInvalidArgument().Trace()
}
// SINGLE SOURCE - Type A: copy(f, f) -> copy(f, f)
// prepareCopyURLsTypeA - prepares target and source clientURLs for copying.
func prepareCopyURLsTypeA(ctx context.Context, sourceURL string, targetURL string, encKeyDB map[string][]prefixSSEPair) URLs {
func prepareCopyURLsTypeA(ctx context.Context, sourceURL, sourceVersion string, targetURL string, encKeyDB map[string][]prefixSSEPair) URLs {
// Extract alias before fiddling with the clientURL.
sourceAlias, _, _ := mustExpandAlias(sourceURL)
// Find alias and expanded clientURL.
targetAlias, targetURL, _ := mustExpandAlias(targetURL)
_, sourceContent, err := url2Stat(ctx, sourceURL, false, encKeyDB)
_, sourceContent, err := url2Stat(ctx, sourceURL, sourceVersion, false, encKeyDB, time.Time{})
if err != nil {
// Source does not exist or insufficient privileges.
return URLs{Error: err.Trace(sourceURL)}
@@ -116,13 +117,13 @@ func makeCopyContentTypeA(sourceAlias string, sourceContent *ClientContent, targ
// SINGLE SOURCE - Type B: copy(f, d) -> copy(f, d/f) -> A
// prepareCopyURLsTypeB - prepares target and source clientURLs for copying.
func prepareCopyURLsTypeB(ctx context.Context, sourceURL string, targetURL string, encKeyDB map[string][]prefixSSEPair) URLs {
func prepareCopyURLsTypeB(ctx context.Context, sourceURL, sourceVersion string, targetURL string, encKeyDB map[string][]prefixSSEPair) URLs {
// Extract alias before fiddling with the clientURL.
sourceAlias, _, _ := mustExpandAlias(sourceURL)
// Find alias and expanded clientURL.
targetAlias, targetURL, _ := mustExpandAlias(targetURL)
_, sourceContent, err := url2Stat(ctx, sourceURL, false, encKeyDB)
_, sourceContent, err := url2Stat(ctx, sourceURL, sourceVersion, false, encKeyDB, time.Time{})
if err != nil {
// Source does not exist or insufficient privileges.
return URLs{Error: err.Trace(sourceURL)}
@@ -150,7 +151,7 @@ func makeCopyContentTypeB(sourceAlias string, sourceContent *ClientContent, targ
// SINGLE SOURCE - Type C: copy(d1..., d2) -> []copy(d1/f, d1/d2/f) -> []A
// prepareCopyRecursiveURLTypeC - prepares target and source clientURLs for copying.
func prepareCopyURLsTypeC(ctx context.Context, sourceURL, targetURL string, isRecursive bool, encKeyDB map[string][]prefixSSEPair) <-chan URLs {
func prepareCopyURLsTypeC(ctx context.Context, sourceURL, targetURL string, isRecursive bool, timeRef time.Time, encKeyDB map[string][]prefixSSEPair) <-chan URLs {
// Extract alias before fiddling with the clientURL.
sourceAlias, _, _ := mustExpandAlias(sourceURL)
// Find alias and expanded clientURL.
@@ -165,8 +166,7 @@ func prepareCopyURLsTypeC(ctx context.Context, sourceURL, targetURL string, isRe
return
}
isIncomplete := false
for sourceContent := range sourceClient.List(ctx, isRecursive, isIncomplete, false, DirNone) {
for sourceContent := range sourceClient.List(ctx, ListOptions{isRecursive: isRecursive, timeRef: timeRef, showDir: DirNone}) {
if sourceContent.Err != nil {
// Listing failed.
copyURLsCh <- URLs{Error: sourceContent.Err.Trace(sourceClient.GetURL().String())}
@@ -200,12 +200,12 @@ func makeCopyContentTypeC(sourceAlias string, sourceURL ClientURL, sourceContent
// MULTI-SOURCE - Type D: copy([](f|d...), d) -> []B
// prepareCopyURLsTypeE - prepares target and source clientURLs for copying.
func prepareCopyURLsTypeD(ctx context.Context, sourceURLs []string, targetURL string, isRecursive bool, encKeyDB map[string][]prefixSSEPair) <-chan URLs {
func prepareCopyURLsTypeD(ctx context.Context, sourceURLs []string, targetURL string, isRecursive bool, timeRef time.Time, encKeyDB map[string][]prefixSSEPair) <-chan URLs {
copyURLsCh := make(chan URLs)
go func(sourceURLs []string, targetURL string, copyURLsCh chan URLs) {
defer close(copyURLsCh)
for _, sourceURL := range sourceURLs {
for cpURLs := range prepareCopyURLsTypeC(ctx, sourceURL, targetURL, isRecursive, encKeyDB) {
for cpURLs := range prepareCopyURLsTypeC(ctx, sourceURL, targetURL, isRecursive, timeRef, encKeyDB) {
copyURLsCh <- cpURLs
}
}
@@ -214,30 +214,30 @@ func prepareCopyURLsTypeD(ctx context.Context, sourceURLs []string, targetURL st
}
// prepareCopyURLs - prepares target and source clientURLs for copying.
func prepareCopyURLs(ctx context.Context, sourceURLs []string, targetURL string, isRecursive bool, encKeyDB map[string][]prefixSSEPair, olderThan, newerThan string) chan URLs {
func prepareCopyURLs(ctx context.Context, sourceURLs []string, targetURL string, isRecursive bool, encKeyDB map[string][]prefixSSEPair, olderThan, newerThan string, timeRef time.Time) chan URLs {
copyURLsCh := make(chan URLs)
go func(sourceURLs []string, targetURL string, copyURLsCh chan URLs, encKeyDB map[string][]prefixSSEPair) {
go func(sourceURLs []string, targetURL string, copyURLsCh chan URLs, encKeyDB map[string][]prefixSSEPair, timeRef time.Time) {
defer close(copyURLsCh)
cpType, err := guessCopyURLType(ctx, sourceURLs, targetURL, isRecursive, encKeyDB)
cpType, cpVersion, err := guessCopyURLType(ctx, sourceURLs, targetURL, isRecursive, encKeyDB, timeRef)
fatalIf(err.Trace(), "Unable to guess the type of copy operation.")
switch cpType {
case copyURLsTypeA:
copyURLsCh <- prepareCopyURLsTypeA(ctx, sourceURLs[0], targetURL, encKeyDB)
copyURLsCh <- prepareCopyURLsTypeA(ctx, sourceURLs[0], cpVersion, targetURL, encKeyDB)
case copyURLsTypeB:
copyURLsCh <- prepareCopyURLsTypeB(ctx, sourceURLs[0], targetURL, encKeyDB)
copyURLsCh <- prepareCopyURLsTypeB(ctx, sourceURLs[0], cpVersion, targetURL, encKeyDB)
case copyURLsTypeC:
for cURLs := range prepareCopyURLsTypeC(ctx, sourceURLs[0], targetURL, isRecursive, encKeyDB) {
for cURLs := range prepareCopyURLsTypeC(ctx, sourceURLs[0], targetURL, isRecursive, timeRef, encKeyDB) {
copyURLsCh <- cURLs
}
case copyURLsTypeD:
for cURLs := range prepareCopyURLsTypeD(ctx, sourceURLs, targetURL, isRecursive, encKeyDB) {
for cURLs := range prepareCopyURLsTypeD(ctx, sourceURLs, targetURL, isRecursive, timeRef, encKeyDB) {
copyURLsCh <- cURLs
}
default:
copyURLsCh <- URLs{Error: errInvalidArgument().Trace(sourceURLs...)}
}
}(sourceURLs, targetURL, copyURLsCh, encKeyDB)
}(sourceURLs, targetURL, copyURLsCh, encKeyDB, timeRef)
finalCopyURLsCh := make(chan URLs)
go func() {
+3 -2
View File
@@ -20,6 +20,7 @@ import (
"context"
"fmt"
"strings"
"time"
"github.com/fatih/color"
"github.com/minio/cli"
@@ -126,7 +127,7 @@ func checkDiffSyntax(ctx context.Context, cliCtx *cli.Context, encKeyDB map[stri
// Diff only works between two directories, verify them below.
// Verify if firstURL is accessible.
_, firstContent, err := url2Stat(ctx, firstURL, false, encKeyDB)
_, firstContent, err := url2Stat(ctx, firstURL, "", false, encKeyDB, time.Time{})
if err != nil {
fatalIf(err.Trace(firstURL), fmt.Sprintf("Unable to stat '%s'.", firstURL))
}
@@ -137,7 +138,7 @@ func checkDiffSyntax(ctx context.Context, cliCtx *cli.Context, encKeyDB map[stri
}
// Verify if secondURL is accessible.
_, secondContent, err := url2Stat(ctx, secondURL, false, encKeyDB)
_, secondContent, err := url2Stat(ctx, secondURL, "", false, encKeyDB, time.Time{})
if err != nil {
fatalIf(err.Trace(secondURL), fmt.Sprintf("Unable to stat '%s'.", secondURL))
}
+2 -3
View File
@@ -167,9 +167,8 @@ func dirDifference(ctx context.Context, sourceClnt, targetClnt Client, sourceURL
func differenceInternal(ctx context.Context, sourceClnt, targetClnt Client, sourceURL, targetURL string, isMetadata bool, isRecursive, returnSimilar bool, dirOpt DirOpt, diffCh chan<- diffMessage) *probe.Error {
// Set default values for listing.
isIncomplete := false // we will not compare any incomplete objects.
srcCh := sourceClnt.List(ctx, isRecursive, isIncomplete, isMetadata, dirOpt)
tgtCh := targetClnt.List(ctx, isRecursive, isIncomplete, isMetadata, dirOpt)
srcCh := sourceClnt.List(ctx, ListOptions{isRecursive: isRecursive, isFetchMeta: isMetadata, showDir: dirOpt})
tgtCh := targetClnt.List(ctx, ListOptions{isRecursive: isRecursive, isFetchMeta: isMetadata, showDir: dirOpt})
srcCtnt, srcOk := <-srcCh
tgtCtnt, tgtOk := <-tgtCh
+1 -3
View File
@@ -105,9 +105,7 @@ func du(urlStr string, depth int, encKeyDB map[string][]prefixSSEPair) (int64, e
return 0, exitStatus(globalErrorExitStatus) // End of journey.
}
isRecursive := false
isIncomplete := false
contentCh := clnt.List(globalContext, isRecursive, isIncomplete, false, DirFirst)
contentCh := clnt.List(globalContext, ListOptions{isRecursive: false, showDir: DirFirst})
size := int64(0)
for content := range contentCh {
if content.Err != nil {
+2 -1
View File
@@ -19,6 +19,7 @@ package cmd
import (
"context"
"strings"
"time"
humanize "github.com/dustin/go-humanize"
"github.com/fatih/color"
@@ -171,7 +172,7 @@ func checkFindSyntax(ctx context.Context, cliCtx *cli.Context, encKeyDB map[stri
// Extract input URLs and validate.
for _, url := range args {
_, _, err := url2Stat(ctx, url, false, encKeyDB)
_, _, err := url2Stat(ctx, url, "", false, encKeyDB, time.Time{})
if err != nil && !isURLPrefixExists(url, false) {
// Bucket name empty is a valid error for 'find myminio' unless we are using watch, treat it as such.
if _, ok := err.ToGoError().(BucketNameEmpty); ok && !cliCtx.Bool("watch") {
+2 -2
View File
@@ -249,7 +249,7 @@ func doFind(ctxCtx context.Context, ctx *findContext) error {
var prevKeyName string
// iterate over all content which is within the given directory
for content := range ctx.clnt.List(globalContext, true, false, false, DirNone) {
for content := range ctx.clnt.List(globalContext, ListOptions{isRecursive: true, showDir: DirNone}) {
if content.Err != nil {
switch content.Err.ToGoError().(type) {
// handle this specifically for filesystem related errors.
@@ -422,7 +422,7 @@ func getShareURL(ctx context.Context, path string) string {
clnt, err := newClientFromAlias(targetAlias, targetURLFull)
fatalIf(err.Trace(targetAlias, targetURLFull), "Unable to initialize client instance from alias.")
content, err := clnt.Stat(ctx, false, false, nil)
content, err := clnt.Stat(ctx, StatOptions{})
fatalIf(err.Trace(targetURLFull, targetAlias), "Unable to lookup file/object.")
// Skip if its a directory.
+1 -1
View File
@@ -111,7 +111,7 @@ func setLegalHold(urlStr string, lhold minio.LegalHoldStatus, isRecursive bool)
alias, _, _ := mustExpandAlias(urlStr)
var cErr error
errorsFound := false
for content := range clnt.List(ctx, isRecursive, false, false, DirNone) {
for content := range clnt.List(ctx, ListOptions{isRecursive: isRecursive, showDir: DirNone}) {
if content.Err != nil {
errorIf(content.Err.Trace(clnt.GetURL().String()), "Unable to list folder.")
cErr = exitStatus(globalErrorExitStatus) // Set the exit status.
+81 -20
View File
@@ -1,5 +1,5 @@
/*
* MinIO Client (C) 2014-2019 MinIO, Inc.
* MinIO Client (C) 2014-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.
@@ -18,16 +18,28 @@ package cmd
import (
"context"
"errors"
"strings"
"time"
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/mc/pkg/ioutils"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/console"
)
// ls specific flags.
var (
lsFlags = []cli.Flag{
cli.StringFlag{
Name: "rewind",
Usage: "back in time",
},
cli.BoolFlag{
Name: "versions",
Usage: "List all versions",
},
cli.BoolFlag{
Name: "recursive, r",
Usage: "list recursively",
@@ -73,11 +85,61 @@ EXAMPLES:
6. List incomplete (previously failed) uploads of objects on Amazon S3.
{{.Prompt}} {{.HelpName}} --incomplete s3/mybucket
7. List contents at a specific time in the past if the bucket versioning is enabled.
{{.Prompt}} {{.HelpName}} --rewind 2020.01.01 s3/mybucket
{{.Prompt}} {{.HelpName}} --rewind 2020.01.01T11:30 s3/mybucket
{{.Prompt}} {{.HelpName}} --rewind 7d s3/mybucket
8. List all contents versions if the bucket versioning is enabled.
{{.Prompt}} {{.HelpName}} --versions s3/mybucket
`,
}
var rewindSupportedFormat = []string{
"2006.01.02",
"2006.01.02T15:04",
"2006.01.02T15:04:05",
time.RFC3339,
}
// Parse rewind flag while considering the system local time zone
func parseRewindFlag(rewind string) (timeRef time.Time) {
if rewind != "" {
location, e := time.LoadLocation("Local")
if e != nil {
return
}
for _, format := range rewindSupportedFormat {
if t, e := time.ParseInLocation(format, rewind, location); e == nil {
timeRef = t
break
}
}
if timeRef.IsZero() {
// rewind is not parsed, check if it is a duration instead
if duration, e := ioutils.ParseDurationTime(rewind); e == nil {
if duration < 0 {
fatalIf(probe.NewError(errors.New("negative duration is not supported")),
"Unable to parse --rewind argument")
}
timeRef = time.Now().Add(-duration)
}
}
if timeRef.IsZero() {
// rewind argument still not parsed, error out
fatalIf(probe.NewError(errors.New("unknown format")), "Unable to parse --rewind argument")
}
}
return
}
// checkListSyntax - validate all the passed arguments
func checkListSyntax(ctx context.Context, cliCtx *cli.Context) {
func checkListSyntax(ctx context.Context, cliCtx *cli.Context) ([]string, bool, bool, time.Time, bool) {
args := cliCtx.Args()
if !cliCtx.Args().Present() {
args = []string{"."}
@@ -87,12 +149,18 @@ func checkListSyntax(ctx context.Context, cliCtx *cli.Context) {
fatalIf(errInvalidArgument().Trace(args...), "Unable to validate empty argument.")
}
}
// extract URLs.
URLs := cliCtx.Args()
isIncomplete := cliCtx.Bool("incomplete")
for _, url := range URLs {
_, _, err := url2Stat(ctx, url, false, nil)
isRecursive := cliCtx.Bool("recursive")
isIncomplete := cliCtx.Bool("incomplete")
withOlderVersions := cliCtx.Bool("versions")
timeRef := parseRewindFlag(cliCtx.String("rewind"))
if timeRef.IsZero() && withOlderVersions {
timeRef = time.Now().UTC()
}
for _, url := range cliCtx.Args() {
_, _, err := url2Stat(ctx, url, "", false, nil, timeRef)
if err != nil && !isURLPrefixExists(url, isIncomplete) {
// Bucket name empty is a valid error for 'ls myminio',
// treat it as such.
@@ -104,6 +172,8 @@ func checkListSyntax(ctx context.Context, cliCtx *cli.Context) {
fatalIf(err.Trace(url), "Unable to stat `"+url+"`.")
}
}
return args, isRecursive, isIncomplete, timeRef, withOlderVersions
}
// mainList - is a handler for mc ls command
@@ -113,22 +183,13 @@ func mainList(cliCtx *cli.Context) error {
// Additional command specific theme customization.
console.SetColor("File", color.New(color.Bold))
console.SetColor("DeletedFile", color.New(color.Bold, color.FgRed))
console.SetColor("Dir", color.New(color.FgCyan, color.Bold))
console.SetColor("Size", color.New(color.FgYellow))
console.SetColor("Time", color.New(color.FgGreen))
// check 'ls' cliCtx arguments.
checkListSyntax(ctx, cliCtx)
// Set command flags from context.
isRecursive := cliCtx.Bool("recursive")
isIncomplete := cliCtx.Bool("incomplete")
args := cliCtx.Args()
// mimic operating system tool behavior.
if !cliCtx.Args().Present() {
args = []string{"."}
}
args, isRecursive, isIncomplete, timeRef, withOlderVersions := checkListSyntax(ctx, cliCtx)
var cErr error
for _, targetURL := range args {
@@ -136,7 +197,7 @@ func mainList(cliCtx *cli.Context) error {
fatalIf(err.Trace(targetURL), "Unable to initialize target `"+targetURL+"`.")
if !strings.HasSuffix(targetURL, string(clnt.GetURL().Separator)) {
var st *ClientContent
st, err = clnt.Stat(ctx, isIncomplete, false, nil)
st, err = clnt.Stat(ctx, StatOptions{incomplete: isIncomplete})
if st != nil && err == nil && st.Type.IsDir() {
targetURL = targetURL + string(clnt.GetURL().Separator)
clnt, err = newClient(targetURL)
@@ -144,7 +205,7 @@ func mainList(cliCtx *cli.Context) error {
}
}
if e := doList(ctx, clnt, isRecursive, isIncomplete); e != nil {
if e := doList(ctx, clnt, isRecursive, isIncomplete, timeRef, withOlderVersions); e != nil {
cErr = e
}
}
+102 -49
View File
@@ -21,6 +21,7 @@ import (
"fmt"
"path/filepath"
"runtime"
"sort"
"strings"
"time"
@@ -44,18 +45,27 @@ type contentMessage struct {
Key string `json:"key"`
ETag string `json:"etag"`
URL string `json:"url,omitempty"`
VersionID string `json:"versionId,omitempty"`
Index int `json:"index,omitempty"`
IsDeleteMarker bool `json:"isDeleteMarker,omitempty"`
}
// String colorized string message.
func (c contentMessage) String() string {
message := console.Colorize("Time", fmt.Sprintf("[%s] ", c.Time.Format(printDate)))
message = message + console.Colorize("Size", fmt.Sprintf("%7s ", strings.Join(strings.Fields(humanize.IBytes(uint64(c.Size))), "")))
message = func() string {
if c.Filetype == "folder" {
return message + console.Colorize("Dir", c.Key)
message += console.Colorize("Size", fmt.Sprintf("%7s ", strings.Join(strings.Fields(humanize.IBytes(uint64(c.Size))), "")))
if c.Filetype == "folder" {
return message + console.Colorize("Dir", c.Key)
}
message += console.Colorize("File", c.Key)
if c.VersionID != "" {
message += console.Colorize("File", fmt.Sprintf(":%d", c.Index))
if c.IsDeleteMarker {
message += console.Colorize("DeletedFile", " (deleted)")
}
return message + console.Colorize("File", c.Key)
}()
}
return message
}
@@ -68,28 +78,6 @@ func (c contentMessage) JSON() string {
return string(jsonMessageBytes)
}
// parseContent parse client Content container into printer struct.
func parseContent(c *ClientContent) contentMessage {
content := contentMessage{}
content.Time = c.Time.Local()
// guess file type.
content.Filetype = func() string {
if c.Type.IsDir() {
return "folder"
}
return "file"
}()
content.Size = c.Size
md5sum := strings.TrimPrefix(c.ETag, "\"")
md5sum = strings.TrimSuffix(md5sum, "\"")
content.ETag = md5sum
// Convert OS Type to match console file printing style.
content.Key = getKey(c)
return content
}
// get content key
func getKey(c *ClientContent) string {
sep := "/"
@@ -106,16 +94,86 @@ func getKey(c *ClientContent) string {
return c.URL.Path
}
// doList - list all entities inside a folder.
func doList(ctx context.Context, clnt Client, isRecursive, isIncomplete bool) error {
// Generate printable listing from a list of client contents
func generateContentMessages(clnt Client, ctnts []*ClientContent) (msgs []contentMessage) {
prefixPath := clnt.GetURL().Path
separator := string(clnt.GetURL().Separator)
if !strings.HasSuffix(prefixPath, separator) {
prefixPath = prefixPath[:strings.LastIndex(prefixPath, separator)+1]
prefixPath = filepath.ToSlash(prefixPath)
if !strings.HasSuffix(prefixPath, "/") {
prefixPath = prefixPath[:strings.LastIndex(prefixPath, "/")+1]
}
prefixPath = strings.TrimPrefix(prefixPath, "./")
var cErr error
for content := range clnt.List(ctx, isRecursive, isIncomplete, false, DirNone) {
for i, c := range ctnts {
// Convert any os specific delimiters to "/".
contentURL := filepath.ToSlash(c.URL.Path)
// Trim prefix path from the content path.
c.URL.Path = strings.TrimPrefix(contentURL, prefixPath)
contentMsg := contentMessage{}
contentMsg.Time = c.Time.Local()
// guess file type.
contentMsg.Filetype = func() string {
if c.Type.IsDir() {
return "folder"
}
return "file"
}()
contentMsg.Size = c.Size
md5sum := strings.TrimPrefix(c.ETag, "\"")
md5sum = strings.TrimSuffix(md5sum, "\"")
contentMsg.ETag = md5sum
// Convert OS Type to match console file printing style.
contentMsg.Key = getKey(c)
contentMsg.VersionID = c.VersionID
contentMsg.IsDeleteMarker = c.IsDeleteMarker
contentMsg.Index = i
// URL is empty by default
// Set it to either relative dir (host) or public url (remote)
contentMsg.URL = clnt.GetURL().String()
msgs = append(msgs, contentMsg)
}
return
}
// Pretty print the list of versions belonging to one object
func printObjectVersions(clnt Client, ctntVersions []*ClientContent) {
// Sort versions
sort.Slice(ctntVersions, func(i, j int) bool {
if ctntVersions[i].IsLatest {
return true
}
if ctntVersions[j].IsLatest {
return false
}
return ctntVersions[i].Time.After(ctntVersions[j].Time)
})
msgs := generateContentMessages(clnt, ctntVersions)
for _, msg := range msgs {
printMsg(msg)
}
}
// doList - list all entities inside a folder.
func doList(ctx context.Context, clnt Client, isRecursive, isIncomplete bool, timeRef time.Time, withOlderVersions bool) error {
var (
lastPath string
perObjectVersions []*ClientContent
cErr error
)
for content := range clnt.List(ctx, ListOptions{
isRecursive: isRecursive,
isIncomplete: isIncomplete,
timeRef: timeRef,
withOlderVersions: withOlderVersions,
withDeleteMarkers: true,
showDir: DirNone,
}) {
if content.Err != nil {
switch content.Err.ToGoError().(type) {
// handle this specifically for filesystem related errors.
@@ -141,21 +199,16 @@ func doList(ctx context.Context, clnt Client, isRecursive, isIncomplete bool) er
continue
}
// Convert any os specific delimiters to "/".
contentURL := filepath.ToSlash(content.URL.Path)
prefixPath = filepath.ToSlash(prefixPath)
if lastPath != content.URL.Path {
// Print any object in the current list before reinitializing it
printObjectVersions(clnt, perObjectVersions)
lastPath = content.URL.Path
perObjectVersions = []*ClientContent{}
}
// Trim prefix of current working dir
prefixPath = strings.TrimPrefix(prefixPath, "."+separator)
// Trim prefix path from the content path.
contentURL = strings.TrimPrefix(contentURL, prefixPath)
content.URL.Path = contentURL
parsedContent := parseContent(content)
// URL is empty by default
// Set it to either relative dir (host) or public url (remote)
parsedContent.URL = clnt.GetURL().String()
// Print colorized or jsonized content info.
printMsg(parsedContent)
perObjectVersions = append(perObjectVersions, content)
}
printObjectVersions(clnt, perObjectVersions)
return cErr
}
+2 -2
View File
@@ -281,7 +281,7 @@ func (mj *mirrorJob) doMirrorWatch(ctx context.Context, targetPath string, tgtSS
// cannot create targetclient
return sURLs.WithError(err)
}
_, err = targetClient.Stat(ctx, false, false, tgtSSE)
_, err = targetClient.Stat(ctx, StatOptions{sse: tgtSSE})
if err == nil {
if !sURLs.SourceContent.RetentionEnabled && !sURLs.SourceContent.LegalHoldEnabled {
return sURLs.WithError(probe.NewError(ObjectAlreadyExists{}))
@@ -826,7 +826,7 @@ func runMirror(ctx context.Context, cancelMirror context.CancelFunc, srcURL, dst
}
}
}
} else if _, err := dstClt.Stat(ctx, false, false, nil); err != nil {
} else if _, err := dstClt.Stat(ctx, StatOptions{}); err != nil {
withLock := false
mode, validity, unit, err := srcClt.GetObjectLockConfig(ctx)
if err == nil {
+2 -1
View File
@@ -21,6 +21,7 @@ import (
"fmt"
"runtime"
"strings"
"time"
"github.com/minio/cli"
"github.com/minio/minio/pkg/wildcard"
@@ -71,7 +72,7 @@ func checkMirrorSyntax(ctx context.Context, cliCtx *cli.Context, encKeyDB map[st
/****** Generic rules *******/
if !cliCtx.Bool("watch") && !cliCtx.Bool("active-active") && !cliCtx.Bool("multi-master") {
_, srcContent, err := url2Stat(ctx, srcURL, false, encKeyDB)
_, srcContent, err := url2Stat(ctx, srcURL, "", false, encKeyDB, time.Time{})
// incomplete uploads are not necessary for mirror operation, no need to verify for them.
isIncomplete := false
if err != nil && !isURLPrefixExists(srcURL, isIncomplete) {
+2 -5
View File
@@ -379,9 +379,6 @@ func runPolicyLinksCmd(args cli.Args, recursive bool) {
// construct new pathes to list public objects
alias, path := url2Alias(targetURL)
isRecursive := recursive
isIncomplete := false
// Iterate over policy rules to fetch public urls, then search
// for objects under those urls
for k, v := range policies {
@@ -401,13 +398,13 @@ func runPolicyLinksCmd(args cli.Args, recursive bool) {
clnt, err := newClient(newURL)
fatalIf(err.Trace(newURL), "Unable to initialize target `"+targetURL+"`.")
// Search for public objects
for content := range clnt.List(globalContext, isRecursive, isIncomplete, false, DirFirst) {
for content := range clnt.List(globalContext, ListOptions{isRecursive: recursive, showDir: DirFirst}) {
if content.Err != nil {
errorIf(content.Err.Trace(clnt.GetURL().String()), "Unable to list folder.")
continue
}
if content.Type.IsDir() && isRecursive {
if content.Type.IsDir() && recursive {
continue
}
+5 -4
View File
@@ -21,6 +21,7 @@ import (
"fmt"
"path/filepath"
"strings"
"time"
"github.com/fatih/color"
"github.com/minio/cli"
@@ -127,7 +128,7 @@ func deleteBucket(ctx context.Context, url string) *probe.Error {
go func() {
defer close(contentCh)
for content := range clnt.List(ctx, true, false, false, DirLast) {
for content := range clnt.List(ctx, ListOptions{isRecursive: true, showDir: DirLast}) {
if content.Err != nil {
contentCh <- content
continue
@@ -177,7 +178,7 @@ func isNamespaceRemoval(ctx context.Context, url string) bool {
//Note: UNC path using / works properly in go 1.9.2 even though it breaks the UNC specification.
url = filepath.ToSlash(filepath.Clean(url))
// namespace removal applies only for non FS. So filter out if passed url represents a directory
if !isAliasURLDir(ctx, url, nil) {
if !isAliasURLDir(ctx, url, nil, time.Time{}) {
_, path := url2Alias(url)
return (path == "")
}
@@ -205,7 +206,7 @@ func mainRemoveBucket(cliCtx *cli.Context) error {
cErr = exitStatus(globalErrorExitStatus)
continue
}
_, err = clnt.Stat(ctx, false, false, nil)
_, err = clnt.Stat(ctx, StatOptions{})
if err != nil {
switch err.ToGoError().(type) {
case BucketNameEmpty:
@@ -218,7 +219,7 @@ func mainRemoveBucket(cliCtx *cli.Context) error {
}
isEmpty := true
for range clnt.List(ctx, true, false, false, DirNone) {
for range clnt.List(ctx, ListOptions{isRecursive: true, showDir: DirNone}) {
isEmpty = false
break
}
+1 -1
View File
@@ -134,7 +134,7 @@ func setRetention(urlStr string, mode minio.RetentionMode, validity uint64, unit
alias, _, _ := mustExpandAlias(urlStr)
var cErr error
for content := range clnt.List(ctx, isRecursive, false, false, DirNone) {
for content := range clnt.List(ctx, ListOptions{isRecursive: isRecursive, showDir: DirNone}) {
if content.Err != nil {
errorIf(content.Err.Trace(clnt.GetURL().String()), "Unable to list folder.")
cErr = exitStatus(globalErrorExitStatus) // Set the exit status.
+3 -3
View File
@@ -23,6 +23,7 @@ import (
"os"
"path/filepath"
"strings"
"time"
"github.com/fatih/color"
"github.com/minio/cli"
@@ -162,7 +163,7 @@ func checkRmSyntax(ctx context.Context, cliCtx *cli.Context, encKeyDB map[string
// Note: UNC path using / works properly in go 1.9.2 even though it breaks the UNC specification.
url = filepath.ToSlash(filepath.Clean(url))
// namespace removal applies only for non FS. So filter out if passed url represents a directory
dir := isAliasURLDir(ctx, url, encKeyDB)
dir := isAliasURLDir(ctx, url, encKeyDB, time.Time{})
if !dir {
_, path := url2Alias(url)
isNamespaceRemoval = (path == "")
@@ -278,8 +279,7 @@ func removeRecursive(url string, isIncomplete, isFake, isBypass bool, olderThan,
errorCh := clnt.Remove(ctx, isIncomplete, isRemoveBucket, isBypass, contentCh)
isRecursive := true
for content := range clnt.List(ctx, isRecursive, isIncomplete, false, DirNone) {
for content := range clnt.List(ctx, ListOptions{isRecursive: true, isIncomplete: isIncomplete, showDir: DirNone}) {
if content.Err != nil {
errorIf(content.Err.Trace(url), "Failed to remove `"+url+"` recursively.")
switch content.Err.ToGoError().(type) {
+3 -5
View File
@@ -94,7 +94,7 @@ func checkShareDownloadSyntax(ctx context.Context, cliCtx *cli.Context, encKeyDB
isRecursive := cliCtx.Bool("recursive")
if !isRecursive {
for _, url := range cliCtx.Args() {
_, _, err := url2Stat(ctx, url, false, encKeyDB)
_, _, err := url2Stat(ctx, url, "", false, encKeyDB, time.Time{})
if err != nil {
fatalIf(err.Trace(url), "Unable to stat `"+url+"`.")
}
@@ -121,12 +121,10 @@ func doShareDownloadURL(ctx context.Context, targetURL string, isRecursive bool,
return err.Trace(shareDownloadsFile)
}
// Generate share URL for each target.
isIncomplete := false
// Channel which will receive objects whose URLs need to be shared
objectsCh := make(chan *ClientContent)
content, err := clnt.Stat(ctx, isIncomplete, false, nil)
content, err := clnt.Stat(ctx, StatOptions{})
if err != nil {
return err.Trace(clnt.GetURL().String())
}
@@ -147,7 +145,7 @@ func doShareDownloadURL(ctx context.Context, targetURL string, isRecursive bool,
// Recursive mode: Share list of objects
go func() {
defer close(objectsCh)
for content := range clnt.List(ctx, isRecursive, isIncomplete, false, DirNone) {
for content := range clnt.List(ctx, ListOptions{isRecursive: isRecursive, showDir: DirNone}) {
objectsCh <- content
}
}()
+3 -2
View File
@@ -29,6 +29,7 @@ import (
"path/filepath"
"regexp"
"strings"
"time"
"github.com/minio/cli"
"github.com/minio/mc/pkg/probe"
@@ -453,7 +454,7 @@ func mainSQL(cliCtx *cli.Context) error {
URLs := cliCtx.Args()
writeHdr := true
for _, url := range URLs {
if _, targetContent, err := url2Stat(ctx, url, false, encKeyDB); err != nil {
if _, targetContent, err := url2Stat(ctx, url, "", false, encKeyDB, time.Time{}); err != nil {
errorIf(err.Trace(url), "Unable to run sql for "+url+".")
continue
} else if !targetContent.Type.IsDir() {
@@ -471,7 +472,7 @@ func mainSQL(cliCtx *cli.Context) error {
continue
}
for content := range clnt.List(ctx, cliCtx.Bool("recursive"), false, false, DirNone) {
for content := range clnt.List(ctx, ListOptions{isRecursive: cliCtx.Bool("recursive"), showDir: DirNone}) {
if content.Err != nil {
errorIf(content.Err.Trace(url), "Unable to list on target `"+url+"`.")
continue
+2 -1
View File
@@ -19,6 +19,7 @@ package cmd
import (
"context"
"strings"
"time"
"github.com/fatih/color"
"github.com/minio/cli"
@@ -90,7 +91,7 @@ func checkStatSyntax(ctx context.Context, cliCtx *cli.Context, encKeyDB map[stri
isIncomplete := false
for _, url := range URLs {
_, _, err := url2Stat(ctx, url, false, encKeyDB)
_, _, err := url2Stat(ctx, url, "", false, encKeyDB, time.Time{})
if err != nil && !isURLPrefixExists(url, isIncomplete) {
fatalIf(err.Trace(url), "Unable to stat `"+url+"`.")
}
+2 -2
View File
@@ -144,7 +144,7 @@ func statURL(ctx context.Context, targetURL string, isIncomplete, isRecursive bo
prefixPath = prefixPath[:strings.LastIndex(prefixPath, separator)+1]
}
var cErr error
for content := range clnt.List(ctx, isRecursive, isIncomplete, false, DirNone) {
for content := range clnt.List(ctx, ListOptions{isRecursive: isRecursive, isIncomplete: isIncomplete, showDir: DirNone}) {
if content.Err != nil {
switch content.Err.ToGoError().(type) {
// handle this specifically for filesystem related errors.
@@ -177,7 +177,7 @@ func statURL(ctx context.Context, targetURL string, isIncomplete, isRecursive bo
return nil, errTargetNotFound(targetURL).Trace(url, standardizedURL)
}
_, stat, err := url2Stat(ctx, url, true, encKeyDB)
_, stat, err := url2Stat(ctx, url, "", true, encKeyDB, time.Time{})
if err != nil {
stat = content
}
+4 -3
View File
@@ -22,6 +22,7 @@ import (
"fmt"
"path/filepath"
"strings"
"time"
"github.com/fatih/color"
"github.com/minio/cli"
@@ -120,7 +121,7 @@ func checkTreeSyntax(ctx context.Context, cliCtx *cli.Context) {
}
for _, url := range args {
if _, _, err := url2Stat(ctx, url, false, nil); err != nil && !isURLPrefixExists(url, false) {
if _, _, err := url2Stat(ctx, url, "", false, nil, time.Time{}); err != nil && !isURLPrefixExists(url, false) {
fatalIf(err.Trace(url), "Unable to tree `"+url+"`.")
}
}
@@ -216,7 +217,7 @@ func doTree(ctx context.Context, url string, level int, leaf bool, branchString
return nil
}
for content := range clnt.List(ctx, false, false, false, DirNone) {
for content := range clnt.List(ctx, ListOptions{isRecursive: false, showDir: DirNone}) {
if !includeFiles && !content.Type.IsDir() {
continue
@@ -278,7 +279,7 @@ func mainTree(cliCtx *cli.Context) error {
}
clnt, err := newClientFromAlias(targetAlias, targetURL)
fatalIf(err.Trace(targetURL), "Unable to initialize target `"+targetURL+"`.")
if e := doList(ctx, clnt, true, false); e != nil {
if e := doList(ctx, clnt, true, false, time.Time{}, false); e != nil {
cErr = e
}
}
+2 -1
View File
@@ -13,7 +13,7 @@ require (
github.com/mattn/go-isatty v0.0.8
github.com/minio/cli v1.22.0
github.com/minio/minio v0.0.0-20200714163805-778e9c864f67
github.com/minio/minio-go/v7 v7.0.2-0.20200718235721-f0e2f3ae3678
github.com/minio/minio-go/v7 v7.0.2-0.20200722162308-e0105ca08252
github.com/minio/sha256-simd v0.1.1
github.com/mitchellh/go-homedir v1.1.0
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e // indirect
@@ -23,6 +23,7 @@ require (
github.com/rjeczalik/notify v0.9.2
golang.org/x/crypto v0.0.0-20200709230013-948cd5f35899
golang.org/x/net v0.0.0-20200707034311-ab3426394381
golang.org/x/sys v0.0.0-20200720211630-cb9d2d5c5666 // indirect
golang.org/x/text v0.3.3
gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f
gopkg.in/h2non/filetype.v1 v1.0.5
+6 -2
View File
@@ -279,8 +279,10 @@ github.com/minio/minio v0.0.0-20200714163805-778e9c864f67 h1:xMg87xvLhrw2jeE6xGx
github.com/minio/minio v0.0.0-20200714163805-778e9c864f67/go.mod h1:0WThPBMICOt5eEGT3XyaUy0cxYmoGhmJEvvRbiVqbYU=
github.com/minio/minio-go/v7 v7.0.0-20200714085548-47e386e2cde8 h1:Xh5yHlXj/367YMabi7tWHol1AslXcuAFWaedBtGgbU0=
github.com/minio/minio-go/v7 v7.0.0-20200714085548-47e386e2cde8/go.mod h1:QTstSRgetEDVpqiEpFniLoCslH4d9cNAa4BtjuRQrwE=
github.com/minio/minio-go/v7 v7.0.2-0.20200718235721-f0e2f3ae3678 h1:vV6dhx+KI1YfQTqlYYUa2dh8MUhecITo1XXhFDTl6fU=
github.com/minio/minio-go/v7 v7.0.2-0.20200718235721-f0e2f3ae3678/go.mod h1:dJ80Mv2HeGkYLH1sqS/ksz07ON6csH3S6JUMSQ2zAns=
github.com/minio/minio-go/v7 v7.0.1 h1:sL2y4uuNUEi7AjvWjoGyDFQKFX2zA0DU2tGM9m3s5f8=
github.com/minio/minio-go/v7 v7.0.1/go.mod h1:dJ80Mv2HeGkYLH1sqS/ksz07ON6csH3S6JUMSQ2zAns=
github.com/minio/minio-go/v7 v7.0.2-0.20200722162308-e0105ca08252 h1:V2JkMDoSmEIhRcMJwX3qeJVOzy1B5bHpHbZaQu77vbs=
github.com/minio/minio-go/v7 v7.0.2-0.20200722162308-e0105ca08252/go.mod h1:dJ80Mv2HeGkYLH1sqS/ksz07ON6csH3S6JUMSQ2zAns=
github.com/minio/sha256-simd v0.1.1 h1:5QHSlgo3nt5yKOJrC7W8w7X+NFl8cMPZm96iu8kKUJU=
github.com/minio/sha256-simd v0.1.1/go.mod h1:B5e1o+1/KgNmWrSQK08Y6Z1Vb5pwIktudl0J58iy0KM=
github.com/minio/simdjson-go v0.1.5-0.20200303142138-b17fe061ea37 h1:pDeao6M5AEd8hwTtGmE0pVKomlL56JFRa5SiXDZAuJE=
@@ -520,6 +522,8 @@ golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd h1:xhmwyvizuTgC2qz7ZlMluP20u
golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200625212154-ddb9806d33ae h1:Ih9Yo4hSPImZOpfGuA4bR/ORKTAbhZo2AbWNRCnevdo=
golang.org/x/sys v0.0.0-20200625212154-ddb9806d33ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200720211630-cb9d2d5c5666 h1:gVCS+QOncANNPlmlO1AhlU3oxs4V9z+gTtPwIk3p2N8=
golang.org/x/sys v0.0.0-20200720211630-cb9d2d5c5666/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.1-0.20181227161524-e6919f6577db/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=