diff --git a/cmd/admin-heal.go b/cmd/admin-heal.go index 0d0731d4..62c8c78d 100644 --- a/cmd/admin-heal.go +++ b/cmd/admin-heal.go @@ -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(false, false, false, DirNone) { + for content := range clnt.List(globalContext, false, false, false, DirNone) { if content.Err != nil { fatalIf(content.Err.Trace(clnt.GetURL().String()), "Unable to heal bucket `"+bucket+"`.") return nil diff --git a/cmd/auto-complete.go b/cmd/auto-complete.go index 19ee3897..86aa1a4f 100644 --- a/cmd/auto-complete.go +++ b/cmd/auto-complete.go @@ -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(false, false, false, DirFirst) { + for content := range clnt.List(globalContext, false, false, false, DirFirst) { cmplS3Path := alias + getKey(content) if content.Type.IsDir() { if !strings.HasSuffix(cmplS3Path, "/") { diff --git a/cmd/cat-main.go b/cmd/cat-main.go index b839fbd3..04fe6e31 100644 --- a/cmd/cat-main.go +++ b/cmd/cat-main.go @@ -18,6 +18,7 @@ package cmd import ( "bytes" + "context" "errors" "fmt" "io" @@ -139,7 +140,7 @@ func checkCatSyntax(ctx *cli.Context) { } // catURL displays contents of a URL to stdout. -func catURL(sourceURL string, encKeyDB map[string][]prefixSSEPair) *probe.Error { +func catURL(ctx context.Context, sourceURL string, encKeyDB map[string][]prefixSSEPair) *probe.Error { var reader io.ReadCloser size := int64(-1) switch sourceURL { @@ -152,11 +153,11 @@ func catURL(sourceURL string, encKeyDB map[string][]prefixSSEPair) *probe.Error // 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(sourceURL, false, encKeyDB) + client, content, err := url2Stat(ctx, sourceURL, false, encKeyDB) if err == nil && client.GetURL().Type == objectStorage { size = content.Size } - if reader, err = getSourceStreamFromURL(sourceURL, encKeyDB); err != nil { + if reader, err = getSourceStreamFromURL(ctx, sourceURL, encKeyDB); err != nil { return err.Trace(sourceURL) } defer reader.Close() @@ -210,17 +211,20 @@ func catOut(r io.Reader, size int64) *probe.Error { } // mainCat is the main entry point for cat command. -func mainCat(ctx *cli.Context) error { +func mainCat(cliCtx *cli.Context) error { + ctx, cancelCat := context.WithCancel(globalContext) + defer cancelCat() + // Parse encryption keys per command. - encKeyDB, err := getEncKeys(ctx) + encKeyDB, err := getEncKeys(cliCtx) fatalIf(err, "Unable to parse encryption keys.") // check 'cat' cli arguments. - checkCatSyntax(ctx) + checkCatSyntax(cliCtx) // Set command flags from context. stdinMode := false - if !ctx.Args().Present() { + if !cliCtx.Args().Present() { stdinMode = true } @@ -231,11 +235,11 @@ func mainCat(ctx *cli.Context) error { } // if Args contain `-`, we need to preserve its order specially. - args := []string(ctx.Args()) - if ctx.Args().First() == "-" { + args := []string(cliCtx.Args()) + if cliCtx.Args().First() == "-" { for i, arg := range os.Args { if arg == "cat" { - // Overwrite ctx.Args with os.Args. + // Overwrite cliCtx.Args with os.Args. args = os.Args[i+1:] break } @@ -244,7 +248,7 @@ func mainCat(ctx *cli.Context) error { // Convert arguments to URLs: expand alias, fix format. for _, url := range args { - fatalIf(catURL(url, encKeyDB).Trace(url), "Unable to read from `"+url+"`.") + fatalIf(catURL(ctx, url, encKeyDB).Trace(url), "Unable to read from `"+url+"`.") } return nil diff --git a/cmd/client-fs.go b/cmd/client-fs.go index d850ec33..734f643a 100644 --- a/cmd/client-fs.go +++ b/cmd/client-fs.go @@ -119,7 +119,7 @@ func (f *fsClient) GetURL() ClientURL { } // Select replies a stream of query results. -func (f *fsClient) Select(expression string, sse encrypt.ServerSide, opts SelectObjectOpts) (io.ReadCloser, *probe.Error) { +func (f *fsClient) Select(ctx context.Context, expression string, sse encrypt.ServerSide, opts SelectObjectOpts) (io.ReadCloser, *probe.Error) { return nil, probe.NewError(APINotImplemented{ API: "Select", APIType: "filesystem", @@ -127,7 +127,7 @@ func (f *fsClient) Select(expression string, sse encrypt.ServerSide, opts Select } // Watches for all fs events on an input path. -func (f *fsClient) Watch(options WatchOptions) (*WatchObject, *probe.Error) { +func (f *fsClient) Watch(ctx context.Context, options WatchOptions) (*WatchObject, *probe.Error) { eventChan := make(chan []EventInfo) errorChan := make(chan *probe.Error) doneChan := make(chan struct{}) @@ -253,7 +253,7 @@ func preserveAttributes(fd *os.File, attr map[string]string) *probe.Error { /// Object operations. -func (f *fsClient) put(reader io.Reader, size int64, metadata map[string][]string, progress io.Reader) (int64, *probe.Error) { +func (f *fsClient) put(ctx context.Context, reader io.Reader, size int64, metadata map[string][]string, progress io.Reader) (int64, *probe.Error) { // ContentType is not handled on purpose. // For filesystem this is a redundant information. @@ -372,13 +372,13 @@ func (f *fsClient) Put(ctx context.Context, reader io.Reader, size int64, metada if metadata[metaDataKey] != "" { meta := make(map[string][]string) meta[metaDataKey] = append(meta[metaDataKey], metadata[metaDataKey]) - return f.put(reader, size, meta, progress) + return f.put(ctx, reader, size, meta, progress) } - return f.put(reader, size, nil, progress) + return f.put(ctx, reader, size, nil, progress) } // ShareDownload - share download not implemented for filesystem. -func (f *fsClient) ShareDownload(expires time.Duration) (string, *probe.Error) { +func (f *fsClient) ShareDownload(ctx context.Context, expires time.Duration) (string, *probe.Error) { return "", probe.NewError(APINotImplemented{ API: "ShareDownload", APIType: "filesystem", @@ -394,7 +394,7 @@ func (f *fsClient) ShareUpload(startsWith bool, expires time.Duration, contentTy } // Copy - copy data from source to destination -func (f *fsClient) Copy(source string, size int64, progress io.Reader, srcSSE, tgtSSE encrypt.ServerSide, metadata map[string]string, disableMultipart bool) *probe.Error { +func (f *fsClient) Copy(ctx context.Context, source string, size int64, progress io.Reader, srcSSE, tgtSSE encrypt.ServerSide, metadata map[string]string, disableMultipart bool) *probe.Error { rc, e := os.Open(source) if e != nil { err := f.toClientError(e, source) @@ -403,14 +403,14 @@ func (f *fsClient) Copy(source string, size int64, progress io.Reader, srcSSE, t defer rc.Close() destination := f.PathURL.Path - if _, err := f.put(rc, size, map[string][]string{}, progress); err != nil { + if _, err := f.put(ctx, rc, size, map[string][]string{}, progress); err != nil { return err.Trace(destination, source) } return nil } // Get returns reader and any additional metadata. -func (f *fsClient) Get(sse encrypt.ServerSide) (io.ReadCloser, *probe.Error) { +func (f *fsClient) Get(ctx context.Context, sse encrypt.ServerSide) (io.ReadCloser, *probe.Error) { fileData, e := os.Open(f.PathURL.Path) if e != nil { err := f.toClientError(e, f.PathURL.Path) @@ -464,7 +464,7 @@ func deleteFile(deletePath string) error { } // Remove - remove entry read from clientContent channel. -func (f *fsClient) Remove(isIncomplete, isRemoveBucket, isBypass bool, contentCh <-chan *ClientContent) <-chan *probe.Error { +func (f *fsClient) Remove(ctx context.Context, isIncomplete, isRemoveBucket, isBypass bool, contentCh <-chan *ClientContent) <-chan *probe.Error { errorCh := make(chan *probe.Error) // Goroutine reads from contentCh and removes the entry in content. @@ -503,7 +503,7 @@ func (f *fsClient) Remove(isIncomplete, isRemoveBucket, isBypass bool, contentCh } // List - list files and folders. -func (f *fsClient) List(isRecursive, isIncomplete, isMetadata bool, showDir DirOpt) <-chan *ClientContent { +func (f *fsClient) List(ctx context.Context, isRecursive, isIncomplete, isMetadata bool, showDir DirOpt) <-chan *ClientContent { contentCh := make(chan *ClientContent) filteredCh := make(chan *ClientContent) @@ -877,7 +877,7 @@ func (f *fsClient) listRecursiveInRoutine(contentCh chan *ClientContent, isMetad } // MakeBucket - create a new bucket. -func (f *fsClient) MakeBucket(region string, ignoreExisting, withLock bool) *probe.Error { +func (f *fsClient) MakeBucket(ctx context.Context, region string, ignoreExisting, withLock bool) *probe.Error { // TODO: ignoreExisting has no effect currently. In the future, we want // to call os.Mkdir() when ignoredExisting is disabled and os.MkdirAll() // otherwise. @@ -890,7 +890,7 @@ func (f *fsClient) MakeBucket(region string, ignoreExisting, withLock bool) *pro } // Set object lock configuration of bucket. -func (f *fsClient) SetObjectLockConfig(mode minio.RetentionMode, validity uint64, unit minio.ValidityUnit) *probe.Error { +func (f *fsClient) SetObjectLockConfig(ctx context.Context, mode minio.RetentionMode, validity uint64, unit minio.ValidityUnit) *probe.Error { return probe.NewError(APINotImplemented{ API: "SetObjectLockConfig", APIType: "filesystem", @@ -898,7 +898,7 @@ func (f *fsClient) SetObjectLockConfig(mode minio.RetentionMode, validity uint64 } // Get object lock configuration of bucket. -func (f *fsClient) GetObjectLockConfig() (mode minio.RetentionMode, validity uint64, unit minio.ValidityUnit, err *probe.Error) { +func (f *fsClient) GetObjectLockConfig(ctx context.Context) (mode minio.RetentionMode, validity uint64, unit minio.ValidityUnit, err *probe.Error) { return "", 0, "", probe.NewError(APINotImplemented{ API: "GetObjectLockConfig", APIType: "filesystem", @@ -906,7 +906,7 @@ func (f *fsClient) GetObjectLockConfig() (mode minio.RetentionMode, validity uin } // GetAccessRules - unsupported API -func (f *fsClient) GetAccessRules() (map[string]string, *probe.Error) { +func (f *fsClient) GetAccessRules(ctx context.Context) (map[string]string, *probe.Error) { return map[string]string{}, probe.NewError(APINotImplemented{ API: "GetBucketPolicy", APIType: "filesystem", @@ -914,7 +914,7 @@ func (f *fsClient) GetAccessRules() (map[string]string, *probe.Error) { } // Set object retention for a given object. -func (f *fsClient) PutObjectRetention(mode minio.RetentionMode, retainUntilDate time.Time, bypassGovernance bool) *probe.Error { +func (f *fsClient) PutObjectRetention(ctx context.Context, mode minio.RetentionMode, retainUntilDate time.Time, bypassGovernance bool) *probe.Error { return probe.NewError(APINotImplemented{ API: "PutObjectRetention", APIType: "filesystem", @@ -922,7 +922,7 @@ func (f *fsClient) PutObjectRetention(mode minio.RetentionMode, retainUntilDate } // Set object legal hold for a given object. -func (f *fsClient) PutObjectLegalHold(lhold minio.LegalHoldStatus) *probe.Error { +func (f *fsClient) PutObjectLegalHold(ctx context.Context, lhold minio.LegalHoldStatus) *probe.Error { return probe.NewError(APINotImplemented{ API: "PutObjectLegalHold", APIType: "filesystem", @@ -930,7 +930,7 @@ func (f *fsClient) PutObjectLegalHold(lhold minio.LegalHoldStatus) *probe.Error } // GetAccess - get access policy permissions. -func (f *fsClient) GetAccess() (access string, policyJSON string, err *probe.Error) { +func (f *fsClient) GetAccess(ctx context.Context) (access string, policyJSON string, err *probe.Error) { // For windows this feature is not implemented. if runtime.GOOS == "windows" { return "", "", probe.NewError(APINotImplemented{API: "GetAccess", APIType: "filesystem"}) @@ -955,7 +955,7 @@ func (f *fsClient) GetAccess() (access string, policyJSON string, err *probe.Err } // SetAccess - set access policy permissions. -func (f *fsClient) SetAccess(access string, isJSON bool) *probe.Error { +func (f *fsClient) SetAccess(ctx context.Context, access string, isJSON bool) *probe.Error { // For windows this feature is not implemented. // JSON policy for fs is not yet implemented. if runtime.GOOS == "windows" || isJSON { @@ -987,7 +987,7 @@ func (f *fsClient) SetAccess(access string, isJSON bool) *probe.Error { } // Stat - get metadata from path. -func (f *fsClient) Stat(isIncomplete, isPreserve bool, sse encrypt.ServerSide) (content *ClientContent, err *probe.Error) { +func (f *fsClient) Stat(ctx context.Context, isIncomplete, isPreserve bool, sse encrypt.ServerSide) (content *ClientContent, err *probe.Error) { st, err := f.fsStat(isIncomplete) if err != nil { return nil, err.Trace(f.PathURL.String()) @@ -1063,7 +1063,7 @@ func (f *fsClient) AddUserAgent(_, _ string) { } // Get Object Tags -func (f *fsClient) GetTags() (*tags.Tags, *probe.Error) { +func (f *fsClient) GetTags(ctx context.Context) (*tags.Tags, *probe.Error) { return nil, probe.NewError(APINotImplemented{ API: "GetObjectTagging", APIType: "filesystem", @@ -1071,7 +1071,7 @@ func (f *fsClient) GetTags() (*tags.Tags, *probe.Error) { } // Set Object tags -func (f *fsClient) SetTags(tags string) *probe.Error { +func (f *fsClient) SetTags(ctx context.Context, tags string) *probe.Error { return probe.NewError(APINotImplemented{ API: "SetObjectTagging", APIType: "filesystem", @@ -1079,7 +1079,7 @@ func (f *fsClient) SetTags(tags string) *probe.Error { } // Delete object tags -func (f *fsClient) DeleteTags() *probe.Error { +func (f *fsClient) DeleteTags(ctx context.Context) *probe.Error { return probe.NewError(APINotImplemented{ API: "DeleteObjectTagging", APIType: "filesystem", @@ -1087,7 +1087,7 @@ func (f *fsClient) DeleteTags() *probe.Error { } // Get lifecycle configuration for a given bucket, not implemented. -func (f *fsClient) GetLifecycle() (ilm.LifecycleConfiguration, *probe.Error) { +func (f *fsClient) GetLifecycle(ctx context.Context) (ilm.LifecycleConfiguration, *probe.Error) { return ilm.LifecycleConfiguration{}, probe.NewError(APINotImplemented{ API: "GetLifecycle", APIType: "filesystem", @@ -1095,7 +1095,7 @@ func (f *fsClient) GetLifecycle() (ilm.LifecycleConfiguration, *probe.Error) { } // Set lifecycle configuration for a given bucket, not implemented. -func (f *fsClient) SetLifecycle(_ ilm.LifecycleConfiguration) *probe.Error { +func (f *fsClient) SetLifecycle(ctx context.Context, _ ilm.LifecycleConfiguration) *probe.Error { return probe.NewError(APINotImplemented{ API: "SetLifecycle", APIType: "filesystem", diff --git a/cmd/client-fs_test.go b/cmd/client-fs_test.go index 2470c1f6..29746b6c 100644 --- a/cmd/client-fs_test.go +++ b/cmd/client-fs_test.go @@ -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(false, false, false, DirNone) { + for content := range fsClient.List(globalContext, false, false, false, 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(false, false, false, DirNone) { + for content := range fsClient.List(globalContext, false, false, false, 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(true, false, false, DirNone) { + for content := range fsClient.List(globalContext, true, false, false, 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(true, false, false, DirNone) { + for content := range fsClient.List(globalContext, true, false, false, DirNone) { if content.Err != nil { err = content.Err break @@ -194,7 +194,7 @@ func (s *TestSuite) TestPutBucket(c *C) { bucketPath := filepath.Join(root, "bucket") fsClient, err := fsNew(bucketPath) c.Assert(err, IsNil) - err = fsClient.MakeBucket("us-east-1", true, false) + err = fsClient.MakeBucket(context.Background(), "us-east-1", true, false) c.Assert(err, IsNil) } @@ -208,9 +208,9 @@ func (s *TestSuite) TestStatBucket(c *C) { fsClient, err := fsNew(bucketPath) c.Assert(err, IsNil) - err = fsClient.MakeBucket("us-east-1", true, false) + err = fsClient.MakeBucket(context.Background(), "us-east-1", true, false) c.Assert(err, IsNil) - _, err = fsClient.Stat(false, false, nil) + _, err = fsClient.Stat(context.Background(), false, false, nil) c.Assert(err, IsNil) } @@ -223,15 +223,15 @@ func (s *TestSuite) TestBucketACLFails(c *C) { bucketPath := filepath.Join(root, "bucket") fsClient, err := fsNew(bucketPath) c.Assert(err, IsNil) - err = fsClient.MakeBucket("us-east-1", true, false) + err = fsClient.MakeBucket(context.Background(), "us-east-1", true, false) c.Assert(err, IsNil) // On windows setting permissions is not supported. if runtime.GOOS != "windows" { - err = fsClient.SetAccess("readonly", false) + err = fsClient.SetAccess(context.Background(), "readonly", false) c.Assert(err, IsNil) - _, _, err = fsClient.GetAccess() + _, _, err = fsClient.GetAccess(context.Background()) 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(nil) + reader, err = fsClient.Get(context.Background(), nil) 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(nil) + reader, err = fsClient.Get(context.Background(), nil) 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(false, false, nil) + content, err := fsClient.Stat(context.Background(), false, false, nil) c.Assert(err, IsNil) c.Assert(content.Size, Equals, int64(dataLen)) } @@ -359,6 +359,6 @@ func (s *TestSuite) TestCopy(c *C) { c.Assert(err, IsNil) c.Assert(n, Equals, int64(len(data))) - err = fsClientTarget.Copy(sourcePath, int64(len(data)), nil, nil, nil, nil, false) + err = fsClientTarget.Copy(context.Background(), sourcePath, int64(len(data)), nil, nil, nil, nil, false) c.Assert(err, IsNil) } diff --git a/cmd/client-s3.go b/cmd/client-s3.go index 022219c7..6631a7f2 100644 --- a/cmd/client-s3.go +++ b/cmd/client-s3.go @@ -232,7 +232,7 @@ func (c *S3Client) GetURL() ClientURL { } // AddNotificationConfig - Add bucket notification -func (c *S3Client) AddNotificationConfig(arn string, events []string, prefix, suffix string, ignoreExisting bool) *probe.Error { +func (c *S3Client) AddNotificationConfig(ctx context.Context, arn string, events []string, prefix, suffix string, ignoreExisting bool) *probe.Error { bucket, _ := c.url2BucketAndObject() // Validate total fields in ARN. fields := strings.Split(arn, ":") @@ -241,7 +241,7 @@ func (c *S3Client) AddNotificationConfig(arn string, events []string, prefix, su } // Get any enabled notification. - mb, e := c.api.GetBucketNotification(bucket) + mb, e := c.api.GetBucketNotificationWithContext(ctx, bucket) if e != nil { return probe.NewError(e) } @@ -297,17 +297,17 @@ func (c *S3Client) AddNotificationConfig(arn string, events []string, prefix, su } // RemoveNotificationConfig - Remove bucket notification -func (c *S3Client) RemoveNotificationConfig(arn string, event string, prefix string, suffix string) *probe.Error { +func (c *S3Client) RemoveNotificationConfig(ctx context.Context, arn string, event string, prefix string, suffix string) *probe.Error { bucket, _ := c.url2BucketAndObject() // Remove all notification configs if arn is empty if arn == "" { - if err := c.api.RemoveAllBucketNotification(bucket); err != nil { + if err := c.api.RemoveAllBucketNotificationWithContext(ctx, bucket); err != nil { return probe.NewError(err) } return nil } - mb, e := c.api.GetBucketNotification(bucket) + mb, e := c.api.GetBucketNotificationWithContext(ctx, bucket) if e != nil { return probe.NewError(e) } @@ -383,10 +383,10 @@ type NotificationConfig struct { } // ListNotificationConfigs - List notification configs -func (c *S3Client) ListNotificationConfigs(arn string) ([]NotificationConfig, *probe.Error) { +func (c *S3Client) ListNotificationConfigs(ctx context.Context, arn string) ([]NotificationConfig, *probe.Error) { var configs []NotificationConfig bucket, _ := c.url2BucketAndObject() - mb, e := c.api.GetBucketNotification(bucket) + mb, e := c.api.GetBucketNotificationWithContext(ctx, bucket) if e != nil { return nil, probe.NewError(e) } @@ -607,7 +607,7 @@ func selectCompressionType(selOpts SelectObjectOpts, object string) minio.Select } // Select - select object content wrapper. -func (c *S3Client) Select(expression string, sse encrypt.ServerSide, selOpts SelectObjectOpts) (io.ReadCloser, *probe.Error) { +func (c *S3Client) Select(ctx context.Context, expression string, sse encrypt.ServerSide, selOpts SelectObjectOpts) (io.ReadCloser, *probe.Error) { opts := minio.SelectObjectOptions{ Expression: expression, ExpressionType: minio.QueryExpressionTypeSQL, @@ -619,7 +619,7 @@ func (c *S3Client) Select(expression string, sse encrypt.ServerSide, selOpts Sel opts.InputSerialization = selectObjectInputOpts(selOpts, object) opts.OutputSerialization = selectObjectOutputOpts(selOpts, opts.InputSerialization) - reader, e := c.api.SelectObjectContent(context.Background(), bucket, object, opts) + reader, e := c.api.SelectObjectContent(ctx, bucket, object, opts) if e != nil { return nil, probe.NewError(e) } @@ -728,7 +728,7 @@ func (c *S3Client) notificationToEventsInfo(ninfo minio.NotificationInfo) []Even } // Watch - Start watching on all bucket events for a given account ID. -func (c *S3Client) Watch(options WatchOptions) (*WatchObject, *probe.Error) { +func (c *S3Client) Watch(ctx context.Context, options WatchOptions) (*WatchObject, *probe.Error) { // Extract bucket and object. bucket, object := c.url2BucketAndObject() @@ -756,7 +756,7 @@ func (c *S3Client) Watch(options WatchOptions) (*WatchObject, *probe.Error) { // The list of buckets to watch var buckets []string if bucket == "" { - bkts, err := c.api.ListBuckets() + bkts, err := c.api.ListBucketsWithContext(ctx) if err != nil { return nil, probe.NewError(err) } @@ -780,7 +780,7 @@ func (c *S3Client) Watch(options WatchOptions) (*WatchObject, *probe.Error) { go func() { defer wg.Done() // Start listening on all bucket events. - eventsCh := c.api.ListenBucketNotification(bucket, options.Prefix, options.Suffix, events, wo.DoneChan) + eventsCh := c.api.ListenBucketNotificationWithContext(ctx, bucket, options.Prefix, options.Suffix, events, wo.DoneChan) for notificationInfo := range eventsCh { if notificationInfo.Err != nil { var perr *probe.Error @@ -811,11 +811,11 @@ func (c *S3Client) Watch(options WatchOptions) (*WatchObject, *probe.Error) { } // Get - get object with metadata. -func (c *S3Client) Get(sse encrypt.ServerSide) (io.ReadCloser, *probe.Error) { +func (c *S3Client) Get(ctx context.Context, sse encrypt.ServerSide) (io.ReadCloser, *probe.Error) { bucket, object := c.url2BucketAndObject() opts := minio.GetObjectOptions{} opts.ServerSideEncryption = sse - reader, e := c.api.GetObject(bucket, object, opts) + reader, e := c.api.GetObjectWithContext(ctx, bucket, object, opts) if e != nil { errResponse := minio.ToErrorResponse(e) if errResponse.Code == "NoSuchBucket" { @@ -839,7 +839,7 @@ func (c *S3Client) Get(sse encrypt.ServerSide) (io.ReadCloser, *probe.Error) { // 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(source string, size int64, progress io.Reader, srcSSE, tgtSSE encrypt.ServerSide, metadata map[string]string, disableMultipart bool) *probe.Error { +func (c *S3Client) Copy(ctx context.Context, source string, size int64, progress io.Reader, srcSSE, tgtSSE encrypt.ServerSide, metadata map[string]string, disableMultipart bool) *probe.Error { dstBucket, dstObject := c.url2BucketAndObject() if dstBucket == "" { return probe.NewError(BucketNameEmpty{}) @@ -881,9 +881,9 @@ func (c *S3Client) Copy(source string, size int64, progress io.Reader, srcSSE, t } if disableMultipart { - e = c.api.CopyObjectWithProgress(dst, src, progress) + e = c.api.CopyObjectWithProgressWithContext(ctx, dst, src, progress) } else { - e = c.api.ComposeObjectWithProgress(dst, []minio.SourceInfo{src}, progress) + e = c.api.ComposeObjectWithProgressWithContext(ctx, dst, []minio.SourceInfo{src}, progress) } if e != nil { @@ -1043,7 +1043,7 @@ func (c *S3Client) Put(ctx context.Context, reader io.Reader, size int64, metada } // Remove incomplete uploads. -func (c *S3Client) removeIncompleteObjects(bucket string, objectsCh <-chan string) <-chan minio.RemoveObjectError { +func (c *S3Client) removeIncompleteObjects(ctx context.Context, bucket string, objectsCh <-chan string) <-chan minio.RemoveObjectError { removeObjectErrorCh := make(chan minio.RemoveObjectError) // Goroutine reads from objectsCh and sends error to removeObjectErrorCh if any. @@ -1051,7 +1051,7 @@ func (c *S3Client) removeIncompleteObjects(bucket string, objectsCh <-chan strin defer close(removeObjectErrorCh) for object := range objectsCh { - if err := c.api.RemoveIncompleteUpload(bucket, object); err != nil { + if err := c.api.RemoveIncompleteUploadWithContext(ctx, bucket, object); err != nil { removeObjectErrorCh <- minio.RemoveObjectError{ObjectName: object, Err: err} } } @@ -1066,7 +1066,7 @@ func (c *S3Client) AddUserAgent(app string, version string) { } // Remove - remove object or bucket(s). -func (c *S3Client) Remove(isIncomplete, isRemoveBucket, isBypass bool, contentCh <-chan *ClientContent) <-chan *probe.Error { +func (c *S3Client) Remove(ctx context.Context, isIncomplete, isRemoveBucket, isBypass bool, contentCh <-chan *ClientContent) <-chan *probe.Error { errorCh := make(chan *probe.Error) prevBucket := "" @@ -1100,9 +1100,9 @@ func (c *S3Client) Remove(isIncomplete, isRemoveBucket, isBypass bool, contentCh objectsCh = make(chan string) prevBucket = bucket if isIncomplete { - statusCh = c.removeIncompleteObjects(bucket, objectsCh) + statusCh = c.removeIncompleteObjects(ctx, bucket, objectsCh) } else { - statusCh = c.api.RemoveObjectsWithOptions(bucket, objectsCh, opts) + statusCh = c.api.RemoveObjectsWithOptionsContext(ctx, bucket, objectsCh, opts) } } @@ -1115,16 +1115,16 @@ func (c *S3Client) Remove(isIncomplete, isRemoveBucket, isBypass bool, contentCh } // Remove bucket if it qualifies. if isRemoveBucket && !isIncomplete { - if err := c.api.RemoveBucket(prevBucket); err != nil { + if err := c.api.RemoveBucketWithContext(ctx, prevBucket); err != nil { errorCh <- probe.NewError(err) } } // Re-init objectsCh for next bucket objectsCh = make(chan string) if isIncomplete { - statusCh = c.removeIncompleteObjects(bucket, objectsCh) + statusCh = c.removeIncompleteObjects(ctx, bucket, objectsCh) } else { - statusCh = c.api.RemoveObjectsWithOptions(bucket, objectsCh, opts) + statusCh = c.api.RemoveObjectsWithOptionsContext(ctx, bucket, objectsCh, opts) } prevBucket = bucket } @@ -1162,7 +1162,7 @@ func (c *S3Client) Remove(isIncomplete, isRemoveBucket, isBypass bool, contentCh } // Remove last bucket if it qualifies. if isRemoveBucket && prevBucket != "" && !isIncomplete { - if err := c.api.RemoveBucket(prevBucket); err != nil { + if err := c.api.RemoveBucketWithContext(ctx, prevBucket); err != nil { errorCh <- probe.NewError(err) } } @@ -1171,7 +1171,7 @@ func (c *S3Client) Remove(isIncomplete, isRemoveBucket, isBypass bool, contentCh } // MakeBucket - make a new bucket. -func (c *S3Client) MakeBucket(region string, ignoreExisting, withLock bool) *probe.Error { +func (c *S3Client) MakeBucket(ctx context.Context, region string, ignoreExisting, withLock bool) *probe.Error { bucket, object := c.url2BucketAndObject() if bucket == "" { return probe.NewError(BucketNameEmpty{}) @@ -1185,7 +1185,7 @@ func (c *S3Client) MakeBucket(region string, ignoreExisting, withLock bool) *pro } var retried bool for { - _, e := c.api.PutObject(bucket, object, + _, e := c.api.PutObjectWithContext(ctx, bucket, object, bytes.NewReader([]byte("")), 0, minio.PutObjectOptions{}) if e == nil { return nil @@ -1196,9 +1196,9 @@ func (c *S3Client) MakeBucket(region string, ignoreExisting, withLock bool) *pro switch minio.ToErrorResponse(e).Code { case "NoSuchBucket": if withLock { - e = c.api.MakeBucketWithObjectLock(bucket, region) + e = c.api.MakeBucketWithObjectLockWithContext(ctx, bucket, region) } else { - e = c.api.MakeBucket(bucket, region) + e = c.api.MakeBucketWithContext(ctx, bucket, region) } if e != nil { return probe.NewError(e) @@ -1212,9 +1212,9 @@ func (c *S3Client) MakeBucket(region string, ignoreExisting, withLock bool) *pro var e error if withLock { - e = c.api.MakeBucketWithObjectLock(bucket, region) + e = c.api.MakeBucketWithObjectLockWithContext(ctx, bucket, region) } else { - e = c.api.MakeBucket(bucket, region) + e = c.api.MakeBucketWithContext(ctx, bucket, region) } if e != nil { // Ignore bucket already existing error when ignoreExisting flag is enabled @@ -1232,13 +1232,13 @@ func (c *S3Client) MakeBucket(region string, ignoreExisting, withLock bool) *pro } // GetAccessRules - get configured policies from the server -func (c *S3Client) GetAccessRules() (map[string]string, *probe.Error) { +func (c *S3Client) GetAccessRules(ctx context.Context) (map[string]string, *probe.Error) { bucket, object := c.url2BucketAndObject() if bucket == "" { return map[string]string{}, probe.NewError(BucketNameEmpty{}) } policies := map[string]string{} - policyStr, e := c.api.GetBucketPolicy(bucket) + policyStr, e := c.api.GetBucketPolicyWithContext(ctx, bucket) if e != nil { return nil, probe.NewError(e) } @@ -1258,12 +1258,12 @@ func (c *S3Client) GetAccessRules() (map[string]string, *probe.Error) { } // GetAccess get access policy permissions. -func (c *S3Client) GetAccess() (string, string, *probe.Error) { +func (c *S3Client) GetAccess(ctx context.Context) (string, string, *probe.Error) { bucket, object := c.url2BucketAndObject() if bucket == "" { return "", "", probe.NewError(BucketNameEmpty{}) } - policyStr, e := c.api.GetBucketPolicy(bucket) + policyStr, e := c.api.GetBucketPolicyWithContext(ctx, bucket) if e != nil { return "", "", probe.NewError(e) } @@ -1282,18 +1282,18 @@ func (c *S3Client) GetAccess() (string, string, *probe.Error) { } // SetAccess set access policy permissions. -func (c *S3Client) SetAccess(bucketPolicy string, isJSON bool) *probe.Error { +func (c *S3Client) SetAccess(ctx context.Context, bucketPolicy string, isJSON bool) *probe.Error { bucket, object := c.url2BucketAndObject() if bucket == "" { return probe.NewError(BucketNameEmpty{}) } if isJSON { - if e := c.api.SetBucketPolicy(bucket, bucketPolicy); e != nil { + if e := c.api.SetBucketPolicyWithContext(ctx, bucket, bucketPolicy); e != nil { return probe.NewError(e) } return nil } - policyStr, e := c.api.GetBucketPolicy(bucket) + policyStr, e := c.api.GetBucketPolicyWithContext(ctx, bucket) if e != nil { return probe.NewError(e) } @@ -1305,7 +1305,7 @@ func (c *S3Client) SetAccess(bucketPolicy string, isJSON bool) *probe.Error { } p.Statements = policy.SetPolicy(p.Statements, policy.BucketPolicy(bucketPolicy), bucket, object) if len(p.Statements) == 0 { - if e = c.api.SetBucketPolicy(bucket, ""); e != nil { + if e = c.api.SetBucketPolicyWithContext(ctx, bucket, ""); e != nil { return probe.NewError(e) } return nil @@ -1314,32 +1314,32 @@ func (c *S3Client) SetAccess(bucketPolicy string, isJSON bool) *probe.Error { if e != nil { return probe.NewError(e) } - if e = c.api.SetBucketPolicy(bucket, string(policyB)); e != nil { + if e = c.api.SetBucketPolicyWithContext(ctx, bucket, string(policyB)); e != nil { return probe.NewError(e) } return nil } // listObjectWrapper - select ObjectList version depending on the target hostname -func (c *S3Client) listObjectWrapper(bucket, object string, isRecursive bool, doneCh chan struct{}, metadata bool) <-chan minio.ObjectInfo { +func (c *S3Client) listObjectWrapper(ctx context.Context, bucket, object string, isRecursive bool, doneCh chan struct{}, metadata bool) <-chan minio.ObjectInfo { if isGoogle(c.targetURL.Host) { // Google Cloud S3 layer doesn't implement ListObjectsV2 implementation // https://github.com/minio/mc/issues/3073 - return c.api.ListObjects(bucket, object, isRecursive, doneCh) + return c.api.ListObjectsV2WithContext(ctx, bucket, object, isRecursive, doneCh) } if metadata { - return c.api.ListObjectsV2WithMetadata(bucket, object, isRecursive, doneCh) + return c.api.ListObjectsV2WithMetadataWithContext(ctx, bucket, object, isRecursive, doneCh) } - return c.api.ListObjectsV2(bucket, object, isRecursive, doneCh) + return c.api.ListObjectsV2WithContext(ctx, bucket, object, isRecursive, doneCh) } -func (c *S3Client) statIncompleteUpload(bucket, object string) (*ClientContent, *probe.Error) { +func (c *S3Client) statIncompleteUpload(ctx context.Context, bucket, object string) (*ClientContent, *probe.Error) { nonRecursive := false objectMetadata := &ClientContent{} // Prefix to pass to minio-go listing in order to fetch a given object/directory prefix := strings.TrimRight(object, string(c.targetURL.Separator)) - for objectMultipartInfo := range c.api.ListIncompleteUploads(bucket, prefix, nonRecursive, nil) { + for objectMultipartInfo := range c.api.ListIncompleteUploadsWithContext(ctx, bucket, prefix, nonRecursive, nil) { if objectMultipartInfo.Err != nil { return nil, probe.NewError(objectMultipartInfo.Err) } @@ -1365,7 +1365,7 @@ func (c *S3Client) statIncompleteUpload(bucket, object string) (*ClientContent, // 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(isIncomplete, isPreserve bool, sse encrypt.ServerSide) (*ClientContent, *probe.Error) { +func (c *S3Client) Stat(ctx context.Context, isIncomplete, isPreserve bool, sse encrypt.ServerSide) (*ClientContent, *probe.Error) { c.Lock() defer c.Unlock() bucket, object := c.url2BucketAndObject() @@ -1376,7 +1376,7 @@ func (c *S3Client) Stat(isIncomplete, isPreserve bool, sse encrypt.ServerSide) ( } if object == "" { - content, err := c.bucketStat(bucket) + content, err := c.bucketStat(ctx, bucket) if err != nil { return nil, err.Trace(bucket) } @@ -1385,7 +1385,7 @@ func (c *S3Client) Stat(isIncomplete, isPreserve bool, sse encrypt.ServerSide) ( // If the request is for incomplete upload stat, handle it here. if isIncomplete { - return c.statIncompleteUpload(bucket, object) + return c.statIncompleteUpload(ctx, bucket, object) } // The following code tries to calculate if a given prefix/object does really exist @@ -1402,7 +1402,7 @@ func (c *S3Client) Stat(isIncomplete, isPreserve bool, sse encrypt.ServerSide) ( if !strings.HasSuffix(object, string(c.targetURL.Separator)) { // 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(bucket, object, opts) + ctnt, err := c.getObjectStat(ctx, bucket, object, opts) if err == nil { return ctnt, err } @@ -1418,7 +1418,7 @@ func (c *S3Client) Stat(isIncomplete, isPreserve bool, sse encrypt.ServerSide) ( // 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(bucket, prefix, nonRecursive, nil, false) { + for objectStat := range c.listObjectWrapper(ctx, bucket, prefix, nonRecursive, nil, false) { if objectStat.Err != nil { return nil, probe.NewError(objectStat.Err) } @@ -1433,8 +1433,8 @@ func (c *S3Client) Stat(isIncomplete, isPreserve bool, sse encrypt.ServerSide) ( } // getObjectStat returns the metadata of an object from a HEAD call. -func (c *S3Client) getObjectStat(bucket, object string, opts minio.StatObjectOptions) (*ClientContent, *probe.Error) { - objectStat, e := c.api.StatObject(bucket, object, opts) +func (c *S3Client) getObjectStat(ctx context.Context, bucket, object string, opts minio.StatObjectOptions) (*ClientContent, *probe.Error) { + objectStat, e := c.api.StatObjectWithContext(ctx, bucket, object, opts) if e != nil { errResponse := minio.ToErrorResponse(e) if errResponse.Code == "AccessDenied" { @@ -1548,7 +1548,7 @@ func (c *S3Client) splitPath(path string) (bucketName, objectName string) { /// Bucket API operations. // List - list at delimited path, if not recursive. -func (c *S3Client) List(isRecursive, isIncomplete, isMetadata bool, showDir DirOpt) <-chan *ClientContent { +func (c *S3Client) List(ctx context.Context, isRecursive, isIncomplete, isMetadata bool, showDir DirOpt) <-chan *ClientContent { c.Lock() defer c.Unlock() @@ -1556,35 +1556,35 @@ func (c *S3Client) List(isRecursive, isIncomplete, isMetadata bool, showDir DirO if isIncomplete { if isRecursive { if showDir == DirNone { - go c.listIncompleteRecursiveInRoutine(contentCh) + go c.listIncompleteRecursiveInRoutine(ctx, contentCh) } else { - go c.listIncompleteRecursiveInRoutineDirOpt(contentCh, showDir) + go c.listIncompleteRecursiveInRoutineDirOpt(ctx, contentCh, showDir) } } else { - go c.listIncompleteInRoutine(contentCh) + go c.listIncompleteInRoutine(ctx, contentCh) } } else { if isRecursive { if showDir == DirNone { - go c.listRecursiveInRoutine(contentCh, isMetadata) + go c.listRecursiveInRoutine(ctx, contentCh, isMetadata) } else { - go c.listRecursiveInRoutineDirOpt(contentCh, showDir, isMetadata) + go c.listRecursiveInRoutineDirOpt(ctx, contentCh, showDir, isMetadata) } } else { - go c.listInRoutine(contentCh, isMetadata) + go c.listInRoutine(ctx, contentCh, isMetadata) } } return contentCh } -func (c *S3Client) listIncompleteInRoutine(contentCh chan *ClientContent) { +func (c *S3Client) listIncompleteInRoutine(ctx context.Context, contentCh chan *ClientContent) { defer close(contentCh) // get bucket and object from URL. b, o := c.url2BucketAndObject() switch { case b == "" && o == "": - buckets, err := c.api.ListBuckets() + buckets, err := c.api.ListBucketsWithContext(ctx) if err != nil { contentCh <- &ClientContent{ Err: probe.NewError(err), @@ -1593,7 +1593,7 @@ func (c *S3Client) listIncompleteInRoutine(contentCh chan *ClientContent) { } isRecursive := false for _, bucket := range buckets { - for object := range c.api.ListIncompleteUploads(bucket.Name, o, isRecursive, nil) { + for object := range c.api.ListIncompleteUploadsWithContext(ctx, bucket.Name, o, isRecursive, nil) { if object.Err != nil { contentCh <- &ClientContent{ Err: probe.NewError(object.Err), @@ -1621,7 +1621,7 @@ func (c *S3Client) listIncompleteInRoutine(contentCh chan *ClientContent) { } default: isRecursive := false - for object := range c.api.ListIncompleteUploads(b, o, isRecursive, nil) { + for object := range c.api.ListIncompleteUploadsWithContext(ctx, b, o, isRecursive, nil) { if object.Err != nil { contentCh <- &ClientContent{ Err: probe.NewError(object.Err), @@ -1649,13 +1649,13 @@ func (c *S3Client) listIncompleteInRoutine(contentCh chan *ClientContent) { } } -func (c *S3Client) listIncompleteRecursiveInRoutine(contentCh chan *ClientContent) { +func (c *S3Client) listIncompleteRecursiveInRoutine(ctx context.Context, contentCh chan *ClientContent) { defer close(contentCh) // get bucket and object from URL. b, o := c.url2BucketAndObject() switch { case b == "" && o == "": - buckets, err := c.api.ListBuckets() + buckets, err := c.api.ListBucketsWithContext(ctx) if err != nil { contentCh <- &ClientContent{ Err: probe.NewError(err), @@ -1664,7 +1664,7 @@ func (c *S3Client) listIncompleteRecursiveInRoutine(contentCh chan *ClientConten } isRecursive := true for _, bucket := range buckets { - for object := range c.api.ListIncompleteUploads(bucket.Name, o, isRecursive, nil) { + for object := range c.api.ListIncompleteUploadsWithContext(ctx, bucket.Name, o, isRecursive, nil) { if object.Err != nil { contentCh <- &ClientContent{ Err: probe.NewError(object.Err), @@ -1683,7 +1683,7 @@ func (c *S3Client) listIncompleteRecursiveInRoutine(contentCh chan *ClientConten } default: isRecursive := true - for object := range c.api.ListIncompleteUploads(b, o, isRecursive, nil) { + for object := range c.api.ListIncompleteUploadsWithContext(ctx, b, o, isRecursive, nil) { if object.Err != nil { contentCh <- &ClientContent{ Err: probe.NewError(object.Err), @@ -1724,7 +1724,7 @@ func (c *S3Client) objectMultipartInfo2ClientContent(bucket string, entry minio. } // Recursively lists incomplete uploads. -func (c *S3Client) listIncompleteRecursiveInRoutineDirOpt(contentCh chan *ClientContent, dirOpt DirOpt) { +func (c *S3Client) listIncompleteRecursiveInRoutineDirOpt(ctx context.Context, 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 @@ -1732,7 +1732,7 @@ func (c *S3Client) listIncompleteRecursiveInRoutineDirOpt(contentCh chan *Client 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) { + for entry := range c.api.ListIncompleteUploadsWithContext(ctx, bucket, object, isRecursive, nil) { if entry.Err != nil { url := c.targetURL.Clone() url.Path = c.joinPath(bucket, object) @@ -1775,14 +1775,14 @@ func (c *S3Client) listIncompleteRecursiveInRoutineDirOpt(contentCh chan *Client if bucket == "" && object == "" { var e error allBuckets = true - buckets, e = c.api.ListBuckets() + buckets, e = c.api.ListBucketsWithContext(ctx) if e != nil { contentCh <- &ClientContent{Err: probe.NewError(e)} return } } else if object == "" { // Get bucket stat if object is empty. - content, err := c.bucketStat(bucket) + content, err := c.bucketStat(ctx, bucket) if err != nil { contentCh <- &ClientContent{Err: err.Trace(bucket)} return @@ -1791,7 +1791,7 @@ func (c *S3Client) listIncompleteRecursiveInRoutineDirOpt(contentCh chan *Client } else if strings.HasSuffix(object, string(c.targetURL.Separator)) { // Get stat of given object is a directory. isIncomplete := true - content, perr := c.Stat(isIncomplete, false, nil) + content, perr := c.Stat(ctx, isIncomplete, false, nil) cContent = content if perr != nil { contentCh <- &ClientContent{Err: perr.Trace(bucket)} @@ -1872,8 +1872,8 @@ func (c *S3Client) objectInfo2ClientContent(bucket string, entry minio.ObjectInf } // Returns bucket stat info of current bucket. -func (c *S3Client) bucketStat(bucket string) (*ClientContent, *probe.Error) { - exists, e := c.api.BucketExists(bucket) +func (c *S3Client) bucketStat(ctx context.Context, bucket string) (*ClientContent, *probe.Error) { + exists, e := c.api.BucketExistsWithContext(ctx, bucket) if e != nil { return nil, probe.NewError(e) } @@ -1884,14 +1884,14 @@ func (c *S3Client) bucketStat(bucket string) (*ClientContent, *probe.Error) { } // Recursively lists objects. -func (c *S3Client) listRecursiveInRoutineDirOpt(contentCh chan *ClientContent, dirOpt DirOpt, metadata bool) { +func (c *S3Client) listRecursiveInRoutineDirOpt(ctx context.Context, contentCh chan *ClientContent, dirOpt DirOpt, metadata bool) { 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, metadata) { + for entry := range c.listObjectWrapper(ctx, bucket, object, isRecursive, nil, metadata) { if entry.Err != nil { url := c.targetURL.Clone() url.Path = c.joinPath(bucket, object) @@ -1933,14 +1933,14 @@ func (c *S3Client) listRecursiveInRoutineDirOpt(contentCh chan *ClientContent, d if bucket == "" && object == "" { var e error allBuckets = true - buckets, e = c.api.ListBuckets() + buckets, e = c.api.ListBucketsWithContext(ctx) if e != nil { contentCh <- &ClientContent{Err: probe.NewError(e)} return } } else if object == "" { // Get bucket stat if object is empty. - content, err := c.bucketStat(bucket) + content, err := c.bucketStat(ctx, bucket) if err != nil { contentCh <- &ClientContent{Err: err.Trace(bucket)} return @@ -1949,7 +1949,7 @@ func (c *S3Client) listRecursiveInRoutineDirOpt(contentCh chan *ClientContent, d } else { // Get stat of given object is a directory. isIncomplete := false - content, perr := c.Stat(isIncomplete, false, nil) + content, perr := c.Stat(ctx, isIncomplete, false, nil) cContent = content if perr != nil { contentCh <- &ClientContent{Err: perr.Trace(bucket)} @@ -1974,13 +1974,13 @@ func (c *S3Client) listRecursiveInRoutineDirOpt(contentCh chan *ClientContent, d } } -func (c *S3Client) listInRoutine(contentCh chan *ClientContent, metadata bool) { +func (c *S3Client) listInRoutine(ctx context.Context, contentCh chan *ClientContent, metadata bool) { defer close(contentCh) // get bucket and object from URL. b, o := c.url2BucketAndObject() switch { case b == "" && o == "": - buckets, e := c.api.ListBuckets() + buckets, e := c.api.ListBucketsWithContext(ctx) if e != nil { contentCh <- &ClientContent{ Err: probe.NewError(e), @@ -1991,7 +1991,7 @@ func (c *S3Client) listInRoutine(contentCh chan *ClientContent, metadata bool) { contentCh <- c.bucketInfo2ClientContent(bucket) } case b != "" && !strings.HasSuffix(c.targetURL.Path, string(c.targetURL.Separator)) && o == "": - content, err := c.bucketStat(b) + content, err := c.bucketStat(ctx, b) if err != nil { contentCh <- &ClientContent{Err: err.Trace(b)} return @@ -1999,7 +1999,7 @@ func (c *S3Client) listInRoutine(contentCh chan *ClientContent, metadata bool) { contentCh <- content default: isRecursive := false - for object := range c.listObjectWrapper(b, o, isRecursive, nil, metadata) { + for object := range c.listObjectWrapper(ctx, b, o, isRecursive, nil, metadata) { if object.Err != nil { contentCh <- &ClientContent{ Err: probe.NewError(object.Err), @@ -2030,13 +2030,13 @@ const ( s3StorageClassGlacier = "GLACIER" ) -func (c *S3Client) listRecursiveInRoutine(contentCh chan *ClientContent, metadata bool) { +func (c *S3Client) listRecursiveInRoutine(ctx context.Context, contentCh chan *ClientContent, metadata bool) { defer close(contentCh) // get bucket and object from URL. b, o := c.url2BucketAndObject() switch { case b == "" && o == "": - buckets, err := c.api.ListBuckets() + buckets, err := c.api.ListBucketsWithContext(ctx) if err != nil { contentCh <- &ClientContent{ Err: probe.NewError(err), @@ -2045,7 +2045,7 @@ func (c *S3Client) listRecursiveInRoutine(contentCh chan *ClientContent, metadat } for _, bucket := range buckets { isRecursive := true - for object := range c.listObjectWrapper(bucket.Name, o, isRecursive, nil, metadata) { + for object := range c.listObjectWrapper(ctx, bucket.Name, o, isRecursive, nil, metadata) { if object.Err != nil { contentCh <- &ClientContent{ Err: probe.NewError(object.Err), @@ -2057,7 +2057,7 @@ func (c *S3Client) listRecursiveInRoutine(contentCh chan *ClientContent, metadat } default: isRecursive := true - for object := range c.listObjectWrapper(b, o, isRecursive, nil, metadata) { + for object := range c.listObjectWrapper(ctx, b, o, isRecursive, nil, metadata) { if object.Err != nil { contentCh <- &ClientContent{ Err: probe.NewError(object.Err), @@ -2070,11 +2070,11 @@ func (c *S3Client) listRecursiveInRoutine(contentCh chan *ClientContent, metadat } // ShareDownload - get a usable presigned object url to share. -func (c *S3Client) ShareDownload(expires time.Duration) (string, *probe.Error) { +func (c *S3Client) ShareDownload(ctx context.Context, expires time.Duration) (string, *probe.Error) { bucket, object := c.url2BucketAndObject() // No additional request parameters are set for the time being. reqParams := make(url.Values) - presignedURL, e := c.api.PresignedGetObject(bucket, object, expires, reqParams) + presignedURL, e := c.api.PresignedGetObjectWithContext(ctx, bucket, object, expires, reqParams) if e != nil { return "", probe.NewError(e) } @@ -2112,20 +2112,20 @@ func (c *S3Client) ShareUpload(isRecursive bool, expires time.Duration, contentT } // SetObjectLockConfig - Set object lock configurataion of bucket. -func (c *S3Client) SetObjectLockConfig(mode minio.RetentionMode, validity uint64, unit minio.ValidityUnit) *probe.Error { +func (c *S3Client) SetObjectLockConfig(ctx context.Context, mode minio.RetentionMode, validity uint64, unit minio.ValidityUnit) *probe.Error { bucket, _ := c.url2BucketAndObject() // FIXME: This is too ugly, fix minio-go vuint := (uint)(validity) if mode != "" && vuint > 0 && unit != "" { - e := c.api.SetBucketObjectLockConfig(bucket, &mode, &vuint, &unit) + e := c.api.SetBucketObjectLockConfigWithContext(ctx, bucket, &mode, &vuint, &unit) if e != nil { return probe.NewError(e).Trace(c.GetURL().String()) } return nil } if mode == "" && vuint == 0 && unit == "" { - e := c.api.SetBucketObjectLockConfig(bucket, nil, nil, nil) + e := c.api.SetBucketObjectLockConfigWithContext(ctx, bucket, nil, nil, nil) if e != nil { return probe.NewError(e).Trace(c.GetURL().String()) } @@ -2135,7 +2135,7 @@ func (c *S3Client) SetObjectLockConfig(mode minio.RetentionMode, validity uint64 } // PutObjectRetention - Set object retention for a given object. -func (c *S3Client) PutObjectRetention(mode minio.RetentionMode, retainUntilDate time.Time, bypassGovernance bool) *probe.Error { +func (c *S3Client) PutObjectRetention(ctx context.Context, mode minio.RetentionMode, retainUntilDate time.Time, bypassGovernance bool) *probe.Error { bucket, object := c.url2BucketAndObject() if mode != "" && !retainUntilDate.IsZero() { @@ -2144,7 +2144,7 @@ func (c *S3Client) PutObjectRetention(mode minio.RetentionMode, retainUntilDate Mode: &mode, GovernanceBypass: bypassGovernance, } - e := c.api.PutObjectRetention(bucket, object, opts) + e := c.api.PutObjectRetentionWithContext(ctx, bucket, object, opts) if e != nil { return probe.NewError(e).Trace(c.GetURL().String()) } @@ -2155,13 +2155,13 @@ func (c *S3Client) PutObjectRetention(mode minio.RetentionMode, retainUntilDate } // PutObjectLegalHold - Set object legal hold for a given object. -func (c *S3Client) PutObjectLegalHold(lhold minio.LegalHoldStatus) *probe.Error { +func (c *S3Client) PutObjectLegalHold(ctx context.Context, lhold minio.LegalHoldStatus) *probe.Error { bucket, object := c.url2BucketAndObject() if lhold.IsValid() { opts := minio.PutObjectLegalHoldOptions{ Status: &lhold, } - e := c.api.PutObjectLegalHold(bucket, object, opts) + e := c.api.PutObjectLegalHoldWithContext(ctx, bucket, object, opts) if e != nil { return probe.NewError(e).Trace(c.GetURL().String()) } @@ -2171,10 +2171,10 @@ func (c *S3Client) PutObjectLegalHold(lhold minio.LegalHoldStatus) *probe.Error } // GetObjectLockConfig - Get object lock configuration of bucket. -func (c *S3Client) GetObjectLockConfig() (minio.RetentionMode, uint64, minio.ValidityUnit, *probe.Error) { +func (c *S3Client) GetObjectLockConfig(ctx context.Context) (minio.RetentionMode, uint64, minio.ValidityUnit, *probe.Error) { bucket, _ := c.url2BucketAndObject() - mode, validity, unit, e := c.api.GetBucketObjectLockConfig(bucket) + mode, validity, unit, e := c.api.GetBucketObjectLockConfigWithContext(ctx, bucket) if e != nil { return "", 0, "", probe.NewError(e).Trace(c.GetURL().String()) } @@ -2189,14 +2189,14 @@ func (c *S3Client) GetObjectLockConfig() (minio.RetentionMode, uint64, minio.Val } // GetTags - Get tags of bucket or object. -func (c *S3Client) GetTags() (*tags.Tags, *probe.Error) { +func (c *S3Client) GetTags(ctx context.Context) (*tags.Tags, *probe.Error) { bucketName, objectName := c.url2BucketAndObject() if bucketName == "" { return nil, probe.NewError(BucketNameEmpty{}) } if objectName == "" { - tags, err := c.api.GetBucketTagging(bucketName) + tags, err := c.api.GetBucketTaggingWithContext(ctx, bucketName) if err != nil { return nil, probe.NewError(err) } @@ -2204,7 +2204,7 @@ func (c *S3Client) GetTags() (*tags.Tags, *probe.Error) { return tags, nil } - s, err := c.api.GetObjectTagging(bucketName, objectName) + s, err := c.api.GetObjectTaggingWithContext(ctx, bucketName, objectName) if err != nil { return nil, probe.NewError(err) } @@ -2218,7 +2218,7 @@ func (c *S3Client) GetTags() (*tags.Tags, *probe.Error) { } // SetTags - Set tags of bucket or object. -func (c *S3Client) SetTags(tagString string) *probe.Error { +func (c *S3Client) SetTags(ctx context.Context, tagString string) *probe.Error { bucketName, objectName := c.url2BucketAndObject() if bucketName == "" { return probe.NewError(BucketNameEmpty{}) @@ -2230,9 +2230,9 @@ func (c *S3Client) SetTags(tagString string) *probe.Error { } if objectName == "" { - err = c.api.SetBucketTagging(bucketName, tags) + err = c.api.SetBucketTaggingWithContext(ctx, bucketName, tags) } else { - err = c.api.PutObjectTagging(bucketName, objectName, tags.ToMap()) + err = c.api.PutObjectTaggingWithContext(ctx, bucketName, objectName, tags.ToMap()) } if err != nil { @@ -2243,7 +2243,7 @@ func (c *S3Client) SetTags(tagString string) *probe.Error { } // DeleteTags - Delete tags of bucket or object -func (c *S3Client) DeleteTags() *probe.Error { +func (c *S3Client) DeleteTags(ctx context.Context) *probe.Error { bucketName, objectName := c.url2BucketAndObject() if bucketName == "" { return probe.NewError(BucketNameEmpty{}) @@ -2251,9 +2251,9 @@ func (c *S3Client) DeleteTags() *probe.Error { var err error if objectName == "" { - err = c.api.DeleteBucketTagging(bucketName) + err = c.api.DeleteBucketTaggingWithContext(ctx, bucketName) } else { - err = c.api.RemoveObjectTagging(bucketName, objectName) + err = c.api.RemoveObjectTaggingWithContext(ctx, bucketName, objectName) } if err != nil { @@ -2264,13 +2264,13 @@ func (c *S3Client) DeleteTags() *probe.Error { } // GetLifecycle - Get current lifecycle configuration. -func (c *S3Client) GetLifecycle() (ilm.LifecycleConfiguration, *probe.Error) { +func (c *S3Client) GetLifecycle(ctx context.Context) (ilm.LifecycleConfiguration, *probe.Error) { bucket, _ := c.url2BucketAndObject() if bucket == "" { return ilm.LifecycleConfiguration{}, probe.NewError(BucketNameEmpty{}) } - lifecycleXML, e := c.api.GetBucketLifecycle(bucket) + lifecycleXML, e := c.api.GetBucketLifecycleWithContext(ctx, bucket) if e != nil { return ilm.LifecycleConfiguration{}, probe.NewError(e) } @@ -2284,7 +2284,7 @@ func (c *S3Client) GetLifecycle() (ilm.LifecycleConfiguration, *probe.Error) { } // SetLifecycle - Set lifecycle configuration on a bucket -func (c *S3Client) SetLifecycle(ilmCfg ilm.LifecycleConfiguration) *probe.Error { +func (c *S3Client) SetLifecycle(ctx context.Context, ilmCfg ilm.LifecycleConfiguration) *probe.Error { bucket, _ := c.url2BucketAndObject() if bucket == "" { return probe.NewError(BucketNameEmpty{}) @@ -2299,7 +2299,7 @@ func (c *S3Client) SetLifecycle(ilmCfg ilm.LifecycleConfiguration) *probe.Error } } - if e := c.api.SetBucketLifecycle(bucket, string(lifecycleXML)); e != nil { + if e := c.api.SetBucketLifecycleWithContext(ctx, bucket, string(lifecycleXML)); e != nil { return probe.NewError(e) } diff --git a/cmd/client-s3_test.go b/cmd/client-s3_test.go index 73044d6b..54793e9d 100644 --- a/cmd/client-s3_test.go +++ b/cmd/client-s3_test.go @@ -171,14 +171,14 @@ func (s *TestSuite) TestBucketOperations(c *C) { s3c, err := S3New(conf) c.Assert(err, IsNil) - err = s3c.MakeBucket("us-east-1", true, false) + err = s3c.MakeBucket(context.Background(), "us-east-1", true, false) c.Assert(err, IsNil) conf.HostURL = server.URL + string(s3c.GetURL().Separator) s3c, err = S3New(conf) c.Assert(err, IsNil) - for content := range s3c.List(false, false, false, DirNone) { + for content := range s3c.List(globalContext, false, false, false, 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(false, false, false, DirNone) { + for content := range s3c.List(globalContext, false, false, false, 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(false, false, false, DirNone) { + for content := range s3c.List(globalContext, false, false, false, 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(nil) + reader, err = s3c.Get(context.Background(), nil) c.Assert(err, IsNil) var buffer bytes.Buffer { diff --git a/cmd/client-url.go b/cmd/client-url.go index b70945e9..86e5c925 100644 --- a/cmd/client-url.go +++ b/cmd/client-url.go @@ -18,6 +18,7 @@ package cmd import ( "bytes" + "context" "path/filepath" "regexp" "runtime" @@ -183,7 +184,7 @@ func urlJoinPath(url1, url2 string) string { } // url2Stat returns stat info for URL. -func url2Stat(urlStr string, fileAttr bool, encKeyDB map[string][]prefixSSEPair) (client Client, content *ClientContent, err *probe.Error) { +func url2Stat(ctx context.Context, urlStr string, fileAttr bool, encKeyDB map[string][]prefixSSEPair) (client Client, content *ClientContent, err *probe.Error) { client, err = newClient(urlStr) if err != nil { return nil, nil, err.Trace(urlStr) @@ -191,7 +192,7 @@ func url2Stat(urlStr string, fileAttr bool, encKeyDB map[string][]prefixSSEPair) alias, _ := url2Alias(urlStr) sse := getSSE(urlStr, encKeyDB[alias]) - content, err = client.Stat(false, fileAttr, sse) + content, err = client.Stat(ctx, false, fileAttr, sse) if err != nil { return nil, nil, err.Trace(urlStr) } @@ -231,7 +232,7 @@ func isURLPrefixExists(urlPrefix string, incomplete bool) bool { isRecursive := false isIncomplete := incomplete isFetchMeta := false - for entry := range clnt.List(isRecursive, isIncomplete, isFetchMeta, DirNone) { + for entry := range clnt.List(globalContext, isRecursive, isIncomplete, isFetchMeta, DirNone) { return entry.Err == nil } return false diff --git a/cmd/client.go b/cmd/client.go index 1bda1a01..f630ebd5 100644 --- a/cmd/client.go +++ b/cmd/client.go @@ -47,56 +47,56 @@ const defaultMultipartThreadsNum = 4 // Client - client interface type Client interface { // Common operations - Stat(isIncomplete, isPreserve bool, sse encrypt.ServerSide) (content *ClientContent, err *probe.Error) - List(isRecursive, isIncomplete, isFetchMeta bool, showDir DirOpt) <-chan *ClientContent + 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 // Bucket operations - MakeBucket(region string, ignoreExisting, withLock bool) *probe.Error + MakeBucket(ctx context.Context, region string, ignoreExisting, withLock bool) *probe.Error // Object lock config - SetObjectLockConfig(mode minio.RetentionMode, validity uint64, unit minio.ValidityUnit) *probe.Error - GetObjectLockConfig() (mode minio.RetentionMode, validity uint64, unit minio.ValidityUnit, perr *probe.Error) + SetObjectLockConfig(ctx context.Context, mode minio.RetentionMode, validity uint64, unit minio.ValidityUnit) *probe.Error + GetObjectLockConfig(ctx context.Context) (mode minio.RetentionMode, validity uint64, unit minio.ValidityUnit, perr *probe.Error) // Access policy operations. - GetAccess() (access string, policyJSON string, error *probe.Error) - GetAccessRules() (policyRules map[string]string, error *probe.Error) - SetAccess(access string, isJSON bool) *probe.Error + GetAccess(ctx context.Context) (access string, policyJSON string, error *probe.Error) + GetAccessRules(ctx context.Context) (policyRules map[string]string, error *probe.Error) + SetAccess(ctx context.Context, access string, isJSON bool) *probe.Error // I/O operations - Copy(source string, size int64, progress io.Reader, srcSSE, tgtSSE encrypt.ServerSide, metadata map[string]string, disableMultipart bool) *probe.Error + Copy(ctx context.Context, source string, size int64, progress io.Reader, srcSSE, tgtSSE encrypt.ServerSide, metadata map[string]string, disableMultipart bool) *probe.Error // Runs select expression on object storage on specific files. - Select(expression string, sse encrypt.ServerSide, opts SelectObjectOpts) (io.ReadCloser, *probe.Error) + Select(ctx context.Context, expression string, sse encrypt.ServerSide, opts SelectObjectOpts) (io.ReadCloser, *probe.Error) // I/O operations with metadata. - Get(sse encrypt.ServerSide) (reader io.ReadCloser, err *probe.Error) + Get(ctx context.Context, sse encrypt.ServerSide) (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 bool) (n int64, err *probe.Error) // Object Locking related API - PutObjectRetention(mode minio.RetentionMode, retainUntilDate time.Time, bypassGovernance bool) *probe.Error - PutObjectLegalHold(hold minio.LegalHoldStatus) *probe.Error + PutObjectRetention(ctx context.Context, mode minio.RetentionMode, retainUntilDate time.Time, bypassGovernance bool) *probe.Error + PutObjectLegalHold(ctx context.Context, hold minio.LegalHoldStatus) *probe.Error // I/O operations with expiration - ShareDownload(expires time.Duration) (string, *probe.Error) + ShareDownload(ctx context.Context, expires time.Duration) (string, *probe.Error) ShareUpload(bool, time.Duration, string) (string, map[string]string, *probe.Error) // Watch events - Watch(options WatchOptions) (*WatchObject, *probe.Error) + Watch(ctx context.Context, options WatchOptions) (*WatchObject, *probe.Error) // Delete operations - Remove(isIncomplete, isRemoveBucket, isBypass bool, contentCh <-chan *ClientContent) (errorCh <-chan *probe.Error) + Remove(ctx context.Context, isIncomplete, isRemoveBucket, isBypass bool, contentCh <-chan *ClientContent) (errorCh <-chan *probe.Error) // GetURL returns back internal url GetURL() ClientURL AddUserAgent(app, version string) // Tagging operations - GetTags() (*tags.Tags, *probe.Error) - SetTags(tags string) *probe.Error - DeleteTags() *probe.Error + GetTags(ctx context.Context) (*tags.Tags, *probe.Error) + SetTags(ctx context.Context, tags string) *probe.Error + DeleteTags(ctx context.Context) *probe.Error // Lifecycle operations - GetLifecycle() (ilm.LifecycleConfiguration, *probe.Error) - SetLifecycle(lfcCfg ilm.LifecycleConfiguration) *probe.Error + GetLifecycle(ctx context.Context) (ilm.LifecycleConfiguration, *probe.Error) + SetLifecycle(ctx context.Context, lfcCfg ilm.LifecycleConfiguration) *probe.Error } // ClientContent - Content container for content metadata diff --git a/cmd/common-methods.go b/cmd/common-methods.go index a91c8f15..f6256cf2 100644 --- a/cmd/common-methods.go +++ b/cmd/common-methods.go @@ -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(aliasURL string, keys map[string][]prefixSSEPair) bool { +func isAliasURLDir(ctx context.Context, aliasURL string, keys map[string][]prefixSSEPair) bool { // If the target url exists, check if it is a directory // and return immediately. - _, targetContent, err := url2Stat(aliasURL, false, keys) + _, targetContent, err := url2Stat(ctx, aliasURL, false, keys) if err == nil { return targetContent.Type.IsDir() } @@ -141,24 +141,24 @@ func isAliasURLDir(aliasURL string, keys map[string][]prefixSSEPair) bool { } // getSourceStreamMetadataFromURL gets a reader from URL. -func getSourceStreamMetadataFromURL(urlStr string, encKeyDB map[string][]prefixSSEPair) (reader io.ReadCloser, +func getSourceStreamMetadataFromURL(ctx context.Context, urlStr string, encKeyDB map[string][]prefixSSEPair) (reader io.ReadCloser, metadata map[string]string, err *probe.Error) { alias, urlStrFull, _, err := expandAlias(urlStr) if err != nil { return nil, nil, err.Trace(urlStr) } sseKey := getSSE(urlStr, encKeyDB[alias]) - return getSourceStream(alias, urlStrFull, true, sseKey, false) + return getSourceStream(ctx, alias, urlStrFull, true, sseKey, false) } // getSourceStreamFromURL gets a reader from URL. -func getSourceStreamFromURL(urlStr string, encKeyDB map[string][]prefixSSEPair) (reader io.ReadCloser, err *probe.Error) { +func getSourceStreamFromURL(ctx context.Context, urlStr string, encKeyDB map[string][]prefixSSEPair) (reader io.ReadCloser, err *probe.Error) { alias, urlStrFull, _, err := expandAlias(urlStr) if err != nil { return nil, err.Trace(urlStr) } sse := getSSE(urlStr, encKeyDB[alias]) - reader, _, err = getSourceStream(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(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 string, urlStr 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(sse) + reader, err = sourceClnt.Get(ctx, sse) if err != nil { return nil, nil, err.Trace(alias, urlStr) } @@ -241,7 +241,7 @@ func getSourceStream(alias string, urlStr string, fetchStat bool, sse encrypt.Se } st.ETag = oinfo.ETag } else { - st, err = sourceClnt.Stat(false, preserve, sse) + st, err = sourceClnt.Stat(ctx, false, preserve, sse) if err != nil { return nil, nil, err.Trace(alias, urlStr) } @@ -290,7 +290,7 @@ func putTargetRetention(ctx context.Context, alias string, urlStr string, metada retainUntilDate = t.UTC() } } - if err := targetClnt.PutObjectRetention(lockMode, retainUntilDate, false); err != nil { + if err := targetClnt.PutObjectRetention(ctx, lockMode, retainUntilDate, false); err != nil { return err.Trace(alias, urlStr) } return nil @@ -334,7 +334,7 @@ func putTargetStreamWithURL(urlStr string, reader io.Reader, size int64, sse enc } // copySourceToTargetURL copies to targetURL from source. -func copySourceToTargetURL(alias, urlStr, source, mode, until, legalHold string, size int64, progress io.Reader, srcSSE, tgtSSE encrypt.ServerSide, metadata map[string]string, disableMultipart bool) *probe.Error { +func copySourceToTargetURL(ctx context.Context, alias, urlStr, source, mode, until, legalHold string, size int64, progress io.Reader, srcSSE, tgtSSE encrypt.ServerSide, metadata map[string]string, disableMultipart bool) *probe.Error { targetClnt, err := newClientFromAlias(alias, urlStr) if err != nil { @@ -344,7 +344,7 @@ func copySourceToTargetURL(alias, urlStr, source, mode, until, legalHold string, metadata[AmzObjectLockMode] = mode metadata[AmzObjectLockRetainUntilDate] = until metadata[AmzObjectLockLegalHold] = legalHold - err = targetClnt.Copy(source, size, progress, srcSSE, tgtSSE, metadata, disableMultipart) + err = targetClnt.Copy(ctx, source, size, progress, srcSSE, tgtSSE, metadata, disableMultipart) if err != nil { return err.Trace(alias, urlStr) @@ -369,13 +369,13 @@ func filterMetadata(metadata map[string]string) map[string]string { // getAllMetadata - returns a map of user defined function // by combining the usermetadata of object and values passed by attr keyword -func getAllMetadata(sourceAlias, sourceURLStr string, srcSSE encrypt.ServerSide, urls URLs, preserve bool) (map[string]string, *probe.Error) { +func getAllMetadata(ctx context.Context, sourceAlias, sourceURLStr string, srcSSE encrypt.ServerSide, urls URLs, preserve bool) (map[string]string, *probe.Error) { metadata := make(map[string]string) sourceClnt, err := newClientFromAlias(sourceAlias, sourceURLStr) if err != nil { return nil, err.Trace(sourceAlias, sourceURLStr) } - st, err := sourceClnt.Stat(false, preserve, srcSSE) + st, err := sourceClnt.Stat(ctx, false, preserve, srcSSE) if err != nil { return nil, err.Trace(sourceAlias, sourceURLStr) } @@ -456,7 +456,7 @@ func uploadSourceToTargetURL(ctx context.Context, urls URLs, progress io.Reader, // If no metadata populated already by the caller // just do a Stat() to obtain the metadata. if len(metadata) == 0 { - metadata, err = getAllMetadata(sourceAlias, sourceURL.String(), srcSSE, urls, preserve) + metadata, err = getAllMetadata(ctx, sourceAlias, sourceURL.String(), srcSSE, urls, preserve) if err != nil { return urls.WithError(err.Trace(sourceURL.String())) } @@ -477,14 +477,14 @@ func uploadSourceToTargetURL(ctx context.Context, urls URLs, progress io.Reader, metadata[k] = v } - err = copySourceToTargetURL(targetAlias, targetURL.String(), sourcePath, mode, until, + err = copySourceToTargetURL(ctx, targetAlias, targetURL.String(), sourcePath, mode, until, legalHold, length, progress, srcSSE, tgtSSE, filterMetadata(metadata), urls.DisableMultipart) } else { if urls.SourceContent.RetentionEnabled { // If no metadata populated already by the caller // just do a Stat() to obtain the metadata. if len(metadata) == 0 { - metadata, err = getAllMetadata(sourceAlias, sourceURL.String(), srcSSE, urls, preserve) + metadata, err = getAllMetadata(ctx, sourceAlias, sourceURL.String(), srcSSE, urls, preserve) if err != nil { return urls.WithError(err.Trace(sourceURL.String())) } @@ -495,7 +495,7 @@ func uploadSourceToTargetURL(ctx context.Context, urls URLs, progress io.Reader, } var reader io.ReadCloser // Proceed with regular stream copy. - reader, metadata, err = getSourceStream(sourceAlias, sourceURL.String(), true, srcSSE, preserve) + reader, metadata, err = getSourceStream(ctx, sourceAlias, sourceURL.String(), true, srcSSE, preserve) if err != nil { return urls.WithError(err.Trace(sourceURL.String())) } diff --git a/cmd/config-host-add.go b/cmd/config-host-add.go index ceea04ea..e9e7554c 100644 --- a/cmd/config-host-add.go +++ b/cmd/config-host-add.go @@ -18,6 +18,7 @@ package cmd import ( "bufio" + "context" "fmt" "math/rand" "os" @@ -159,7 +160,7 @@ func addHost(alias string, hostCfgV9 hostConfigV9) { // probeS3Signature - auto probe S3 server signature: issue a Stat call // using v4 signature then v2 in case of failure. -func probeS3Signature(accessKey, secretKey, url string) (string, *probe.Error) { +func probeS3Signature(ctx context.Context, accessKey, secretKey, url string) (string, *probe.Error) { probeBucketName := randString(60, rand.NewSource(time.Now().UnixNano()), "probe-bucket-sign-") // Test s3 connection for API auto probe s3Config := &Config{ @@ -178,7 +179,7 @@ func probeS3Signature(accessKey, secretKey, url string) (string, *probe.Error) { return "", err } - if _, err := s3Client.Stat(false, false, nil); err != nil { + if _, err := s3Client.Stat(ctx, false, false, nil); err != nil { e := err.ToGoError() if _, ok := e.(BucketDoesNotExist); ok { // Bucket doesn't exist, means signature probing worked successfully. @@ -209,7 +210,7 @@ func probeS3Signature(accessKey, secretKey, url string) (string, *probe.Error) { // BuildS3Config constructs an S3 Config and does // signature auto-probe when needed. -func BuildS3Config(url, accessKey, secretKey, api, lookup string) (*Config, *probe.Error) { +func BuildS3Config(ctx context.Context, url, accessKey, secretKey, api, lookup string) (*Config, *probe.Error) { s3Config := NewS3Config(url, &hostConfigV9{ AccessKey: accessKey, @@ -225,7 +226,7 @@ func BuildS3Config(url, accessKey, secretKey, api, lookup string) (*Config, *pro return s3Config, nil } // Probe S3 signature version - api, err := probeS3Signature(accessKey, secretKey, url) + api, err := probeS3Signature(ctx, accessKey, secretKey, url) if err != nil { return nil, err.Trace(url, accessKey, secretKey, api, lookup) } @@ -272,21 +273,24 @@ func fetchHostKeys(args cli.Args) (string, string) { return accessKey, secretKey } -func mainConfigHostAdd(ctx *cli.Context) error { +func mainConfigHostAdd(cli *cli.Context) error { console.SetColor("HostMessage", color.New(color.FgGreen)) var ( - args = ctx.Args() + args = cli.Args() alias = cleanAlias(args.Get(0)) url = trimTrailingSeparator(args.Get(1)) - api = ctx.String("api") - lookup = ctx.String("lookup") + api = cli.String("api") + lookup = cli.String("lookup") ) accessKey, secretKey := fetchHostKeys(args) - checkConfigHostAddSyntax(ctx, accessKey, secretKey) + checkConfigHostAddSyntax(cli, accessKey, secretKey) - s3Config, err := BuildS3Config(url, accessKey, secretKey, api, lookup) - fatalIf(err.Trace(ctx.Args()...), "Unable to initialize new config from the provided credentials.") + ctx, cancelHostAdd := context.WithCancel(globalContext) + defer cancelHostAdd() + + s3Config, err := BuildS3Config(ctx, url, accessKey, secretKey, api, lookup) + fatalIf(err.Trace(cli.Args()...), "Unable to initialize new config from the provided credentials.") addHost(alias, hostConfigV9{ URL: s3Config.HostURL, diff --git a/cmd/cp-main.go b/cmd/cp-main.go index 9fa25983..31d804a1 100644 --- a/cmd/cp-main.go +++ b/cmd/cp-main.go @@ -244,28 +244,28 @@ func doCopy(ctx context.Context, cpURLs URLs, pg ProgressReader, encKeyDB map[st urls := uploadSourceToTargetURL(ctx, cpURLs, pg, encKeyDB, preserve) if isMvCmd && urls.Error == nil { - bgRemove(sourcePath) + bgRemove(ctx, sourcePath) } return urls } // doCopyFake - Perform a fake copy to update the progress bar appropriately. -func doCopyFake(cpURLs URLs, pg Progress, isMvCmd bool) URLs { +func doCopyFake(ctx context.Context, cpURLs URLs, pg Progress, isMvCmd bool) URLs { if progressReader, ok := pg.(*progressBar); ok { progressReader.ProgressBar.Add64(cpURLs.SourceContent.Size) } if isMvCmd { sourcePath := filepath.ToSlash(filepath.Join(cpURLs.SourceAlias, cpURLs.SourceContent.URL.Path)) - bgRemove(sourcePath) + bgRemove(ctx, sourcePath) } return cpURLs } // doPrepareCopyURLs scans the source URL and prepares a list of objects for copying. -func doPrepareCopyURLs(session *sessionV8, cancelCopy context.CancelFunc) (totalBytes, totalObjects int64) { +func doPrepareCopyURLs(ctx context.Context, session *sessionV8, cancelCopy context.CancelFunc) (totalBytes, totalObjects int64) { // Separate source and target. 'cp' can take only one target, // but any number of sources. sourceURLs := session.Header.CommandArgs[:len(session.Header.CommandArgs)-1] @@ -289,7 +289,7 @@ func doPrepareCopyURLs(session *sessionV8, cancelCopy context.CancelFunc) (total scanBar = scanBarFactory() } - URLsCh := prepareCopyURLs(sourceURLs, targetURL, isRecursive, encKeyDB, olderThan, newerThan) + URLsCh := prepareCopyURLs(ctx, sourceURLs, targetURL, isRecursive, encKeyDB, olderThan, newerThan) done := false for !done { select { @@ -341,10 +341,7 @@ func doPrepareCopyURLs(session *sessionV8, cancelCopy context.CancelFunc) (total return } -func doCopySession(cli *cli.Context, session *sessionV8, encKeyDB map[string][]prefixSSEPair, isMvCmd bool) error { - ctx, cancelCopy := context.WithCancel(globalContext) - defer cancelCopy() - +func doCopySession(ctx context.Context, cancelCopy context.CancelFunc, cli *cli.Context, session *sessionV8, encKeyDB map[string][]prefixSSEPair, isMvCmd bool) error { var isCopied func(string) bool var totalObjects, totalBytes int64 @@ -366,7 +363,7 @@ func doCopySession(cli *cli.Context, session *sessionV8, encKeyDB map[string][]p isCopied = isLastFactory(session.Header.LastCopied) if !session.HasData() { - totalBytes, totalObjects = doPrepareCopyURLs(session, cancelCopy) + totalBytes, totalObjects = doPrepareCopyURLs(ctx, session, cancelCopy) } else { totalBytes, totalObjects = session.Header.TotalBytes, session.Header.TotalObjects } @@ -403,7 +400,7 @@ func doCopySession(cli *cli.Context, session *sessionV8, encKeyDB map[string][]p go func() { totalBytes := int64(0) - for cpURLs := range prepareCopyURLs(sourceURLs, targetURL, isRecursive, + for cpURLs := range prepareCopyURLs(ctx, sourceURLs, targetURL, isRecursive, encKeyDB, olderThan, newerThan) { if cpURLs.Error != nil { // Print in new line and adjust to top so that we @@ -509,7 +506,7 @@ func doCopySession(cli *cli.Context, session *sessionV8, encKeyDB map[string][]p // Verify if previously copied, notify progress bar. if isCopied != nil && isCopied(cpURLs.SourceContent.URL.String()) { queueCh <- func() URLs { - return doCopyFake(cpURLs, pg, isMvCmd) + return doCopyFake(ctx, cpURLs, pg, isMvCmd) } } else { queueCh <- func() URLs { @@ -618,33 +615,36 @@ func getMetaDataEntry(metadataString string) (map[string]string, *probe.Error) { } // mainCopy is the entry point for cp command. -func mainCopy(ctx *cli.Context) error { +func mainCopy(cliCtx *cli.Context) error { + ctx, cancelCopy := context.WithCancel(globalContext) + defer cancelCopy() + // Parse encryption keys per command. - encKeyDB, err := getEncKeys(ctx) + encKeyDB, err := getEncKeys(cliCtx) fatalIf(err, "Unable to parse encryption keys.") // Parse metadata. userMetaMap := make(map[string]string) - if ctx.String("attr") != "" { - userMetaMap, err = getMetaDataEntry(ctx.String("attr")) - fatalIf(err, "Unable to parse attribute %v", ctx.String("attr")) + if cliCtx.String("attr") != "" { + userMetaMap, err = getMetaDataEntry(cliCtx.String("attr")) + fatalIf(err, "Unable to parse attribute %v", cliCtx.String("attr")) } // check 'copy' cli arguments. - checkCopySyntax(ctx, encKeyDB, false) + checkCopySyntax(ctx, cliCtx, encKeyDB, false) // Additional command specific theme customization. console.SetColor("Copy", color.New(color.FgGreen, color.Bold)) - recursive := ctx.Bool("recursive") - olderThan := ctx.String("older-than") - newerThan := ctx.String("newer-than") - storageClass := ctx.String("storage-class") - retentionMode := ctx.String(rmFlag) - retentionDuration := ctx.String(rdFlag) - legalHold := strings.ToUpper(ctx.String(lhFlag)) + recursive := cliCtx.Bool("recursive") + olderThan := cliCtx.String("older-than") + newerThan := cliCtx.String("newer-than") + storageClass := cliCtx.String("storage-class") + retentionMode := cliCtx.String(rmFlag) + retentionDuration := cliCtx.String(rdFlag) + legalHold := strings.ToUpper(cliCtx.String(lhFlag)) sseKeys := os.Getenv("MC_ENCRYPT_KEY") - if key := ctx.String("encrypt-key"); key != "" { + if key := cliCtx.String("encrypt-key"); key != "" { sseKeys = key } @@ -652,12 +652,12 @@ func mainCopy(ctx *cli.Context) error { sseKeys, err = getDecodedKey(sseKeys) fatalIf(err, "Unable to parse encryption keys.") } - sse := ctx.String("encrypt") + sse := cliCtx.String("encrypt") var session *sessionV8 - if ctx.Bool("continue") { - sessionID := getHash("cp", ctx.Args()) + if cliCtx.Bool("continue") { + sessionID := getHash("cp", cliCtx.Args()) if isSessionExists(sessionID) { session, err = loadSessionV8(sessionID) fatalIf(err.Trace(sessionID), "Unable to load session.") @@ -673,14 +673,14 @@ func mainCopy(ctx *cli.Context) error { session.Header.CommandStringFlags[lhFlag] = legalHold session.Header.CommandStringFlags["encrypt-key"] = sseKeys session.Header.CommandStringFlags["encrypt"] = sse - session.Header.CommandBoolFlags["session"] = ctx.Bool("continue") + session.Header.CommandBoolFlags["session"] = cliCtx.Bool("continue") - if ctx.Bool("preserve") { - session.Header.CommandBoolFlags["preserve"] = ctx.Bool("preserve") + if cliCtx.Bool("preserve") { + session.Header.CommandBoolFlags["preserve"] = cliCtx.Bool("preserve") } session.Header.UserMetaData = userMetaMap - session.Header.CommandBoolFlags["md5"] = ctx.Bool("md5") - session.Header.CommandBoolFlags["disable-multipart"] = ctx.Bool("disable-multipart") + session.Header.CommandBoolFlags["md5"] = cliCtx.Bool("md5") + session.Header.CommandBoolFlags["disable-multipart"] = cliCtx.Bool("disable-multipart") var e error if session.Header.RootPath, e = os.Getwd(); e != nil { @@ -689,11 +689,11 @@ func mainCopy(ctx *cli.Context) error { } // extract URLs. - session.Header.CommandArgs = ctx.Args() + session.Header.CommandArgs = cliCtx.Args() } } - e := doCopySession(ctx, session, encKeyDB, false) + e := doCopySession(ctx, cancelCopy, cliCtx, session, encKeyDB, false) if session != nil { session.Delete() } diff --git a/cmd/cp-url-syntax.go b/cmd/cp-url-syntax.go index 3f3f4388..fd1abc0e 100644 --- a/cmd/cp-url-syntax.go +++ b/cmd/cp-url-syntax.go @@ -17,6 +17,7 @@ package cmd import ( + "context" "fmt" "runtime" @@ -24,27 +25,27 @@ import ( "github.com/minio/minio/pkg/console" ) -func checkCopySyntax(ctx *cli.Context, encKeyDB map[string][]prefixSSEPair, isMvCmd bool) { - if len(ctx.Args()) < 2 { +func checkCopySyntax(ctx context.Context, cliCtx *cli.Context, encKeyDB map[string][]prefixSSEPair, isMvCmd bool) { + if len(cliCtx.Args()) < 2 { if isMvCmd { - cli.ShowCommandHelpAndExit(ctx, "mv", 1) // last argument is exit code. + cli.ShowCommandHelpAndExit(cliCtx, "mv", 1) // last argument is exit code. } - cli.ShowCommandHelpAndExit(ctx, "cp", 1) // last argument is exit code. + cli.ShowCommandHelpAndExit(cliCtx, "cp", 1) // last argument is exit code. } // extract URLs. - URLs := ctx.Args() + URLs := cliCtx.Args() if len(URLs) < 2 { - fatalIf(errDummy().Trace(ctx.Args()...), "Unable to parse source and target arguments.") + fatalIf(errDummy().Trace(cliCtx.Args()...), "Unable to parse source and target arguments.") } srcURLs := URLs[:len(URLs)-1] tgtURL := URLs[len(URLs)-1] - isRecursive := ctx.Bool("recursive") + isRecursive := cliCtx.Bool("recursive") // Verify if source(s) exists. for _, srcURL := range srcURLs { - _, _, err := url2Stat(srcURL, false, encKeyDB) + _, _, err := url2Stat(ctx, srcURL, false, encKeyDB) if err != nil { console.Fatalf("Unable to validate source %s\n", srcURL) } @@ -58,11 +59,11 @@ func checkCopySyntax(ctx *cli.Context, encKeyDB map[string][]prefixSSEPair, isMv } } - if ctx.String(rdFlag) != "" && ctx.String(rmFlag) == "" { + if cliCtx.String(rdFlag) != "" && cliCtx.String(rmFlag) == "" { fatalIf(errInvalidArgument().Trace(), fmt.Sprintf("Both object retention flags `--%s` and `--%s` are required.\n", rdFlag, rmFlag)) } - if ctx.String(rdFlag) == "" && ctx.String(rmFlag) != "" { + if cliCtx.String(rdFlag) == "" && cliCtx.String(rmFlag) != "" { fatalIf(errInvalidArgument().Trace(), fmt.Sprintf("Both object retention flags `--%s` and `--%s` are required.\n", rdFlag, rmFlag)) } @@ -72,38 +73,38 @@ func checkCopySyntax(ctx *cli.Context, encKeyDB map[string][]prefixSSEPair, isMv } // Guess CopyURLsType based on source and target URLs. - copyURLsType, err := guessCopyURLType(srcURLs, tgtURL, isRecursive, encKeyDB) + copyURLsType, err := guessCopyURLType(ctx, srcURLs, tgtURL, isRecursive, encKeyDB) if err != nil { fatalIf(errInvalidArgument().Trace(), "Unable to guess the type of "+operation+" operation.") } switch copyURLsType { case copyURLsTypeA: // File -> File. - checkCopySyntaxTypeA(srcURLs, tgtURL, encKeyDB, isMvCmd) + checkCopySyntaxTypeA(ctx, srcURLs, tgtURL, encKeyDB, isMvCmd) case copyURLsTypeB: // File -> Folder. - checkCopySyntaxTypeB(srcURLs, tgtURL, encKeyDB, isMvCmd) + checkCopySyntaxTypeB(ctx, srcURLs, tgtURL, encKeyDB, isMvCmd) case copyURLsTypeC: // Folder... -> Folder. - checkCopySyntaxTypeC(srcURLs, tgtURL, isRecursive, encKeyDB, isMvCmd) + checkCopySyntaxTypeC(ctx, srcURLs, tgtURL, isRecursive, encKeyDB, isMvCmd) case copyURLsTypeD: // File1...FileN -> Folder. - checkCopySyntaxTypeD(srcURLs, tgtURL, encKeyDB, isMvCmd) + checkCopySyntaxTypeD(ctx, srcURLs, tgtURL, encKeyDB, isMvCmd) default: fatalIf(errInvalidArgument().Trace(), "Unable to guess the type of "+operation+" operation.") } // Preserve functionality not supported for windows - if ctx.Bool("preserve") && runtime.GOOS == "windows" { + if cliCtx.Bool("preserve") && runtime.GOOS == "windows" { fatalIf(errInvalidArgument().Trace(), "Permissions are not preserved on windows platform.") } } // checkCopySyntaxTypeA verifies if the source and target are valid file arguments. -func checkCopySyntaxTypeA(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) { // Check source. if len(srcURLs) != 1 { fatalIf(errInvalidArgument().Trace(), "Invalid number of source arguments.") } srcURL := srcURLs[0] - _, srcContent, err := url2Stat(srcURL, false, keys) + _, srcContent, err := url2Stat(ctx, srcURL, false, keys) fatalIf(err.Trace(srcURL), "Unable to stat source `"+srcURL+"`.") if !srcContent.Type.IsRegular() { @@ -112,13 +113,13 @@ func checkCopySyntaxTypeA(srcURLs []string, tgtURL string, keys map[string][]pre } // checkCopySyntaxTypeB verifies if the source is a valid file and target is a valid folder. -func checkCopySyntaxTypeB(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) { // Check source. if len(srcURLs) != 1 { fatalIf(errInvalidArgument().Trace(), "Invalid number of source arguments.") } srcURL := srcURLs[0] - _, srcContent, err := url2Stat(srcURL, false, keys) + _, srcContent, err := url2Stat(ctx, srcURL, false, keys) fatalIf(err.Trace(srcURL), "Unable to stat source `"+srcURL+"`.") if !srcContent.Type.IsRegular() { @@ -126,7 +127,7 @@ func checkCopySyntaxTypeB(srcURLs []string, tgtURL string, keys map[string][]pre } // Check target. - if _, tgtContent, err := url2Stat(tgtURL, false, keys); err == nil { + if _, tgtContent, err := url2Stat(ctx, tgtURL, false, keys); err == nil { if !tgtContent.Type.IsDir() { fatalIf(errInvalidArgument().Trace(tgtURL), "Target `"+tgtURL+"` is not a folder.") } @@ -134,21 +135,21 @@ func checkCopySyntaxTypeB(srcURLs []string, tgtURL string, keys map[string][]pre } // checkCopySyntaxTypeC verifies if the source is a valid recursive dir and target is a valid folder. -func checkCopySyntaxTypeC(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) { // Check source. if len(srcURLs) != 1 { fatalIf(errInvalidArgument().Trace(), "Invalid number of source arguments.") } // Check target. - if _, tgtContent, err := url2Stat(tgtURL, false, keys); err == nil { + if _, tgtContent, err := url2Stat(ctx, tgtURL, false, keys); err == nil { if !tgtContent.Type.IsDir() { fatalIf(errInvalidArgument().Trace(tgtURL), "Target `"+tgtURL+"` is not a folder.") } } for _, srcURL := range srcURLs { - c, srcContent, err := url2Stat(srcURL, false, keys) + c, srcContent, err := url2Stat(ctx, srcURL, false, keys) // incomplete uploads are not necessary for copy operation, no need to verify for them. isIncomplete := false if err != nil { @@ -183,10 +184,10 @@ func checkCopySyntaxTypeC(srcURLs []string, tgtURL string, isRecursive bool, key } // checkCopySyntaxTypeD verifies if the source is a valid list of files and target is a valid folder. -func checkCopySyntaxTypeD(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) { // Source can be anything: file, dir, dir... // Check target if it is a dir - if _, tgtContent, err := url2Stat(tgtURL, false, keys); err == nil { + if _, tgtContent, err := url2Stat(ctx, tgtURL, false, keys); err == nil { if !tgtContent.Type.IsDir() { fatalIf(errInvalidArgument().Trace(tgtURL), "Target `"+tgtURL+"` is not a folder.") } diff --git a/cmd/cp-url.go b/cmd/cp-url.go index 57a5cc17..d2733a3f 100644 --- a/cmd/cp-url.go +++ b/cmd/cp-url.go @@ -17,6 +17,7 @@ package cmd import ( + "context" "os" "path/filepath" "strings" @@ -51,10 +52,10 @@ const ( // guessCopyURLType guesses the type of clientURL. This approach all allows prepareURL // functions to accurately report failure causes. -func guessCopyURLType(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) (copyURLsType, *probe.Error) { if len(sourceURLs) == 1 { // 1 Source, 1 Target sourceURL := sourceURLs[0] - _, sourceContent, err := url2Stat(sourceURL, false, keys) + _, sourceContent, err := url2Stat(ctx, sourceURL, false, keys) if err != nil { return copyURLsTypeInvalid, err } @@ -66,7 +67,7 @@ func guessCopyURLType(sourceURLs []string, targetURL string, isRecursive bool, k } // If target is a folder, it is Type B. - if isAliasURLDir(targetURL, keys) { + if isAliasURLDir(ctx, targetURL, keys) { return copyURLsTypeB, nil } // else Type A. @@ -74,7 +75,7 @@ func guessCopyURLType(sourceURLs []string, targetURL string, isRecursive bool, k } // Multiple source args and target is a folder. It is Type D. - if isAliasURLDir(targetURL, keys) { + if isAliasURLDir(ctx, targetURL, keys) { return copyURLsTypeD, nil } @@ -83,13 +84,13 @@ func guessCopyURLType(sourceURLs []string, targetURL string, isRecursive bool, k // SINGLE SOURCE - Type A: copy(f, f) -> copy(f, f) // prepareCopyURLsTypeA - prepares target and source clientURLs for copying. -func prepareCopyURLsTypeA(sourceURL string, targetURL string, encKeyDB map[string][]prefixSSEPair) URLs { +func prepareCopyURLsTypeA(ctx context.Context, sourceURL 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(sourceURL, false, encKeyDB) + _, sourceContent, err := url2Stat(ctx, sourceURL, false, encKeyDB) 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(sourceURL string, targetURL string, encKeyDB map[string][]prefixSSEPair) URLs { +func prepareCopyURLsTypeB(ctx context.Context, sourceURL 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(sourceURL, false, encKeyDB) + _, sourceContent, err := url2Stat(ctx, sourceURL, false, encKeyDB) 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(sourceURL, targetURL string, isRecursive bool, encKeyDB map[string][]prefixSSEPair) <-chan URLs { +func prepareCopyURLsTypeC(ctx context.Context, sourceURL, targetURL string, isRecursive bool, encKeyDB map[string][]prefixSSEPair) <-chan URLs { // Extract alias before fiddling with the clientURL. sourceAlias, _, _ := mustExpandAlias(sourceURL) // Find alias and expanded clientURL. @@ -166,7 +167,7 @@ func prepareCopyURLsTypeC(sourceURL, targetURL string, isRecursive bool, encKeyD } isIncomplete := false - for sourceContent := range sourceClient.List(isRecursive, isIncomplete, false, DirNone) { + for sourceContent := range sourceClient.List(ctx, isRecursive, isIncomplete, false, DirNone) { if sourceContent.Err != nil { // Listing failed. copyURLsCh <- URLs{Error: sourceContent.Err.Trace(sourceClient.GetURL().String())} @@ -212,12 +213,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(sourceURLs []string, targetURL string, isRecursive bool, encKeyDB map[string][]prefixSSEPair) <-chan URLs { +func prepareCopyURLsTypeD(ctx context.Context, sourceURLs []string, targetURL string, isRecursive bool, 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(sourceURL, targetURL, isRecursive, encKeyDB) { + for cpURLs := range prepareCopyURLsTypeC(ctx, sourceURL, targetURL, isRecursive, encKeyDB) { copyURLsCh <- cpURLs } } @@ -226,24 +227,24 @@ func prepareCopyURLsTypeD(sourceURLs []string, targetURL string, isRecursive boo } // prepareCopyURLs - prepares target and source clientURLs for copying. -func prepareCopyURLs(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) chan URLs { copyURLsCh := make(chan URLs) go func(sourceURLs []string, targetURL string, copyURLsCh chan URLs, encKeyDB map[string][]prefixSSEPair) { defer close(copyURLsCh) - cpType, err := guessCopyURLType(sourceURLs, targetURL, isRecursive, encKeyDB) + cpType, err := guessCopyURLType(ctx, sourceURLs, targetURL, isRecursive, encKeyDB) fatalIf(err.Trace(), "Unable to guess the type of copy operation.") switch cpType { case copyURLsTypeA: - copyURLsCh <- prepareCopyURLsTypeA(sourceURLs[0], targetURL, encKeyDB) + copyURLsCh <- prepareCopyURLsTypeA(ctx, sourceURLs[0], targetURL, encKeyDB) case copyURLsTypeB: - copyURLsCh <- prepareCopyURLsTypeB(sourceURLs[0], targetURL, encKeyDB) + copyURLsCh <- prepareCopyURLsTypeB(ctx, sourceURLs[0], targetURL, encKeyDB) case copyURLsTypeC: - for cURLs := range prepareCopyURLsTypeC(sourceURLs[0], targetURL, isRecursive, encKeyDB) { + for cURLs := range prepareCopyURLsTypeC(ctx, sourceURLs[0], targetURL, isRecursive, encKeyDB) { copyURLsCh <- cURLs } case copyURLsTypeD: - for cURLs := range prepareCopyURLsTypeD(sourceURLs, targetURL, isRecursive, encKeyDB) { + for cURLs := range prepareCopyURLsTypeD(ctx, sourceURLs, targetURL, isRecursive, encKeyDB) { copyURLsCh <- cURLs } default: diff --git a/cmd/diff-main.go b/cmd/diff-main.go index c32eddfa..94270ba5 100644 --- a/cmd/diff-main.go +++ b/cmd/diff-main.go @@ -17,6 +17,7 @@ package cmd import ( + "context" "fmt" "strings" @@ -109,23 +110,23 @@ func (d diffMessage) JSON() string { return string(diffJSONBytes) } -func checkDiffSyntax(ctx *cli.Context, encKeyDB map[string][]prefixSSEPair) { - if len(ctx.Args()) != 2 { - cli.ShowCommandHelpAndExit(ctx, "diff", 1) // last argument is exit code +func checkDiffSyntax(ctx context.Context, cliCtx *cli.Context, encKeyDB map[string][]prefixSSEPair) { + if len(cliCtx.Args()) != 2 { + cli.ShowCommandHelpAndExit(cliCtx, "diff", 1) // last argument is exit code } - for _, arg := range ctx.Args() { + for _, arg := range cliCtx.Args() { if strings.TrimSpace(arg) == "" { - fatalIf(errInvalidArgument().Trace(ctx.Args()...), "Unable to validate empty argument.") + fatalIf(errInvalidArgument().Trace(cliCtx.Args()...), "Unable to validate empty argument.") } } - URLs := ctx.Args() + URLs := cliCtx.Args() firstURL := URLs[0] secondURL := URLs[1] // Diff only works between two directories, verify them below. // Verify if firstURL is accessible. - _, firstContent, err := url2Stat(firstURL, false, encKeyDB) + _, firstContent, err := url2Stat(ctx, firstURL, false, encKeyDB) if err != nil { fatalIf(err.Trace(firstURL), fmt.Sprintf("Unable to stat '%s'.", firstURL)) } @@ -136,7 +137,7 @@ func checkDiffSyntax(ctx *cli.Context, encKeyDB map[string][]prefixSSEPair) { } // Verify if secondURL is accessible. - _, secondContent, err := url2Stat(secondURL, false, encKeyDB) + _, secondContent, err := url2Stat(ctx, secondURL, false, encKeyDB) if err != nil { fatalIf(err.Trace(secondURL), fmt.Sprintf("Unable to stat '%s'.", secondURL)) } @@ -189,13 +190,16 @@ func doDiffMain(firstURL, secondURL string) error { } // mainDiff main for 'diff'. -func mainDiff(ctx *cli.Context) error { +func mainDiff(cliCtx *cli.Context) error { + ctx, cancelDiff := context.WithCancel(globalContext) + defer cancelDiff() + // Parse encryption keys per command. - encKeyDB, err := getEncKeys(ctx) + encKeyDB, err := getEncKeys(cliCtx) fatalIf(err, "Unable to parse encryption keys.") // check 'diff' cli arguments. - checkDiffSyntax(ctx, encKeyDB) + checkDiffSyntax(ctx, cliCtx, encKeyDB) // Additional command specific theme customization. console.SetColor("DiffMessage", color.New(color.FgGreen, color.Bold)) @@ -206,7 +210,7 @@ func mainDiff(ctx *cli.Context) error { console.SetColor("DiffMetadata", color.New(color.FgYellow, color.Bold)) console.SetColor("DiffMMSourceMTime", color.New(color.FgYellow, color.Bold)) - URLs := ctx.Args() + URLs := cliCtx.Args() firstURL := URLs.Get(0) secondURL := URLs.Get(1) diff --git a/cmd/difference.go b/cmd/difference.go index 2e6ca841..aa38b96e 100644 --- a/cmd/difference.go +++ b/cmd/difference.go @@ -138,8 +138,8 @@ func dirDifference(sourceClnt, targetClnt Client, sourceURL, targetURL string) ( func differenceInternal(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(isRecursive, isIncomplete, isMetadata, dirOpt) - tgtCh := targetClnt.List(isRecursive, isIncomplete, isMetadata, dirOpt) + srcCh := sourceClnt.List(globalContext, isRecursive, isIncomplete, isMetadata, dirOpt) + tgtCh := targetClnt.List(globalContext, isRecursive, isIncomplete, isMetadata, dirOpt) srcCtnt, srcOk := <-srcCh tgtCtnt, tgtOk := <-tgtCh diff --git a/cmd/du-main.go b/cmd/du-main.go index 7715a2b2..2f66a5de 100644 --- a/cmd/du-main.go +++ b/cmd/du-main.go @@ -107,7 +107,7 @@ func du(urlStr string, depth int, encKeyDB map[string][]prefixSSEPair) (int64, e isRecursive := false isIncomplete := false - contentCh := clnt.List(isRecursive, isIncomplete, false, DirFirst) + contentCh := clnt.List(globalContext, isRecursive, isIncomplete, false, DirFirst) size := int64(0) for content := range contentCh { if content.Err != nil { diff --git a/cmd/event-add.go b/cmd/event-add.go index 31efc3eb..cbf7f6f5 100644 --- a/cmd/event-add.go +++ b/cmd/event-add.go @@ -17,6 +17,7 @@ package cmd import ( + "context" "strings" "github.com/fatih/color" @@ -104,19 +105,22 @@ func (u eventAddMessage) String() string { return msg } -func mainEventAdd(ctx *cli.Context) error { +func mainEventAdd(cliCtx *cli.Context) error { + ctx, cancelEventAdd := context.WithCancel(globalContext) + defer cancelEventAdd() + console.SetColor("Event", color.New(color.FgGreen, color.Bold)) - checkEventAddSyntax(ctx) + checkEventAddSyntax(cliCtx) - args := ctx.Args() + args := cliCtx.Args() path := args[0] arn := args[1] - ignoreExisting := ctx.Bool("p") + ignoreExisting := cliCtx.Bool("p") - event := strings.Split(ctx.String("event"), ",") - prefix := ctx.String("prefix") - suffix := ctx.String("suffix") + event := strings.Split(cliCtx.String("event"), ",") + prefix := cliCtx.String("prefix") + suffix := cliCtx.String("suffix") client, err := newClient(path) if err != nil { @@ -128,7 +132,7 @@ func mainEventAdd(ctx *cli.Context) error { fatalIf(errDummy().Trace(), "The provided url doesn't point to a S3 server.") } - err = s3Client.AddNotificationConfig(arn, event, prefix, suffix, ignoreExisting) + err = s3Client.AddNotificationConfig(ctx, arn, event, prefix, suffix, ignoreExisting) fatalIf(err, "Cannot enable notification on the specified bucket.") printMsg(eventAddMessage{ ARN: arn, diff --git a/cmd/event-list.go b/cmd/event-list.go index 22e42a3b..dda60b85 100644 --- a/cmd/event-list.go +++ b/cmd/event-list.go @@ -17,6 +17,7 @@ package cmd import ( + "context" "fmt" "github.com/fatih/color" @@ -96,14 +97,17 @@ func (u eventListMessage) String() string { return msg } -func mainEventList(ctx *cli.Context) error { +func mainEventList(cliCtx *cli.Context) error { + ctx, cancelEventList := context.WithCancel(globalContext) + defer cancelEventList() + console.SetColor("ARN", color.New(color.FgGreen, color.Bold)) console.SetColor("Event", color.New(color.FgCyan, color.Bold)) console.SetColor("Filter", color.New(color.Bold)) - checkEventListSyntax(ctx) + checkEventListSyntax(cliCtx) - args := ctx.Args() + args := cliCtx.Args() path := args[0] arn := "" if len(args) > 1 { @@ -120,7 +124,7 @@ func mainEventList(ctx *cli.Context) error { fatalIf(errDummy().Trace(), "The provided url doesn't point to a S3 server.") } - configs, err := s3Client.ListNotificationConfigs(arn) + configs, err := s3Client.ListNotificationConfigs(ctx, arn) fatalIf(err, "Cannot list notifications on the specified bucket.") for _, config := range configs { diff --git a/cmd/event-remove.go b/cmd/event-remove.go index 8b68076c..9b7b6819 100644 --- a/cmd/event-remove.go +++ b/cmd/event-remove.go @@ -17,6 +17,7 @@ package cmd import ( + "context" "errors" "github.com/minio/minio-go/v6" @@ -102,12 +103,15 @@ func (u eventRemoveMessage) String() string { return msg } -func mainEventRemove(ctx *cli.Context) error { +func mainEventRemove(cliCtx *cli.Context) error { + ctx, cancelEventRemove := context.WithCancel(globalContext) + defer cancelEventRemove() + console.SetColor("Event", color.New(color.FgGreen, color.Bold)) - checkEventRemoveSyntax(ctx) + checkEventRemoveSyntax(cliCtx) - args := ctx.Args() + args := cliCtx.Args() path := args.Get(0) arn := "" @@ -126,11 +130,11 @@ func mainEventRemove(ctx *cli.Context) error { } // flags for the attributes of the even - event := ctx.String("event") - prefix := ctx.String("prefix") - suffix := ctx.String("suffix") + event := cliCtx.String("event") + prefix := cliCtx.String("prefix") + suffix := cliCtx.String("suffix") - err = s3Client.RemoveNotificationConfig(arn, event, prefix, suffix) + err = s3Client.RemoveNotificationConfig(ctx, arn, event, prefix, suffix) if err != nil { if err.Cause == minio.ErrNoNotificationConfigMatch { fatalIf(err, "Remove event failed.") diff --git a/cmd/find-main.go b/cmd/find-main.go index f12cfc06..1625c87e 100644 --- a/cmd/find-main.go +++ b/cmd/find-main.go @@ -17,6 +17,7 @@ package cmd import ( + "context" "strings" humanize "github.com/dustin/go-humanize" @@ -154,8 +155,8 @@ EXAMPLES: } // checkFindSyntax - validate the passed arguments -func checkFindSyntax(ctx *cli.Context, encKeyDB map[string][]prefixSSEPair) { - args := ctx.Args() +func checkFindSyntax(ctx context.Context, cliCtx *cli.Context, encKeyDB map[string][]prefixSSEPair) { + args := cliCtx.Args() if !args.Present() { args = []string{"./"} // No args just default to present directory. } else if args.Get(0) == "." { @@ -170,10 +171,10 @@ func checkFindSyntax(ctx *cli.Context, encKeyDB map[string][]prefixSSEPair) { // Extract input URLs and validate. for _, url := range args { - _, _, err := url2Stat(url, false, encKeyDB) + _, _, err := url2Stat(ctx, url, false, encKeyDB) 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 && !ctx.Bool("watch") { + if _, ok := err.ToGoError().(BucketNameEmpty); ok && !cliCtx.Bool("watch") { continue } fatalIf(err.Trace(url), "Unable to stat `"+url+"`.") @@ -207,18 +208,21 @@ type findContext struct { } // mainFind - handler for mc find commands -func mainFind(ctx *cli.Context) error { +func mainFind(cliCtx *cli.Context) error { + ctx, cancelFind := context.WithCancel(globalContext) + defer cancelFind() + // Additional command specific theme customization. console.SetColor("Find", color.New(color.FgGreen, color.Bold)) console.SetColor("FindExecErr", color.New(color.FgRed, color.Italic, color.Bold)) // Parse encryption keys per command. - encKeyDB, err := getEncKeys(ctx) + encKeyDB, err := getEncKeys(cliCtx) fatalIf(err, "Unable to parse encryption keys.") - checkFindSyntax(ctx, encKeyDB) + checkFindSyntax(ctx, cliCtx, encKeyDB) - args := ctx.Args() + args := cliCtx.Args() if !args.Present() { args = []string{"./"} // Not args present default to present directory. } else if args.Get(0) == "." { @@ -230,11 +234,11 @@ func mainFind(ctx *cli.Context) error { var olderThan, newerThan string - if ctx.String("older-than") != "" { - olderThan = ctx.String("older-than") + if cliCtx.String("older-than") != "" { + olderThan = cliCtx.String("older-than") } - if ctx.String("newer-than") != "" { - newerThan = ctx.String("newer-than") + if cliCtx.String("newer-than") != "" { + newerThan = cliCtx.String("newer-than") } // Use 'e' to indicate Go error, this is a convention followed in `mc`. For probe.Error we call it @@ -242,14 +246,14 @@ func mainFind(ctx *cli.Context) error { var e error var largerSize, smallerSize uint64 - if ctx.String("larger") != "" { - largerSize, e = humanize.ParseBytes(ctx.String("larger")) - fatalIf(probe.NewError(e).Trace(ctx.String("larger")), "Unable to parse input bytes.") + if cliCtx.String("larger") != "" { + largerSize, e = humanize.ParseBytes(cliCtx.String("larger")) + fatalIf(probe.NewError(e).Trace(cliCtx.String("larger")), "Unable to parse input bytes.") } - if ctx.String("smaller") != "" { - smallerSize, e = humanize.ParseBytes(ctx.String("smaller")) - fatalIf(probe.NewError(e).Trace(ctx.String("smaller")), "Unable to parse input bytes.") + if cliCtx.String("smaller") != "" { + smallerSize, e = humanize.ParseBytes(cliCtx.String("smaller")) + fatalIf(probe.NewError(e).Trace(cliCtx.String("smaller")), "Unable to parse input bytes.") } targetAlias, _, hostCfg, err := expandAlias(args[0]) @@ -260,20 +264,20 @@ func mainFind(ctx *cli.Context) error { targetFullURL = hostCfg.URL } - return doFind(&findContext{ - Context: ctx, - maxDepth: ctx.Uint("maxdepth"), - execCmd: ctx.String("exec"), - printFmt: ctx.String("print"), - namePattern: ctx.String("name"), - pathPattern: ctx.String("path"), - regexPattern: ctx.String("regex"), - ignorePattern: ctx.String("ignore"), + return doFind(ctx, &findContext{ + Context: cliCtx, + maxDepth: cliCtx.Uint("maxdepth"), + execCmd: cliCtx.String("exec"), + printFmt: cliCtx.String("print"), + namePattern: cliCtx.String("name"), + pathPattern: cliCtx.String("path"), + regexPattern: cliCtx.String("regex"), + ignorePattern: cliCtx.String("ignore"), olderThan: olderThan, newerThan: newerThan, largerSize: largerSize, smallerSize: smallerSize, - watch: ctx.Bool("watch"), + watch: cliCtx.Bool("watch"), targetAlias: targetAlias, targetURL: args[0], targetFullURL: targetFullURL, diff --git a/cmd/find.go b/cmd/find.go index 16f856ba..94931438 100644 --- a/cmd/find.go +++ b/cmd/find.go @@ -18,6 +18,7 @@ package cmd import ( "bytes" + "context" "os" "os/exec" "path/filepath" @@ -131,7 +132,7 @@ func execFind(command string) { // watchFind - enables listening on the input path, listens for all file/object // created actions. Asynchronously executes the input command line, also allows // formatting for the command line in accordance with subsititution arguments. -func watchFind(ctx *findContext) { +func watchFind(ctxCtx context.Context, ctx *findContext) { // Watch is not enabled, return quickly. if !ctx.watch { return @@ -140,7 +141,7 @@ func watchFind(ctx *findContext) { Recursive: true, Events: []string{"put"}, } - watchObj, err := ctx.clnt.Watch(options) + watchObj, err := ctx.clnt.Watch(ctxCtx, options) fatalIf(err.Trace(ctx.targetAlias), "Cannot watch with given options.") // Loop until user CTRL-C the command line. @@ -162,7 +163,7 @@ func watchFind(ctx *findContext) { continue } - find(ctx, contentMessage{ + find(ctxCtx, ctx, contentMessage{ Key: getAliasedPath(ctx, event.Path), Time: time, Size: event.Size, @@ -220,7 +221,7 @@ func getAliasedPath(ctx *findContext, path string) string { return trimSuffixAtMaxDepth(ctx.targetURL, aliasedPath, separator, ctx.maxDepth) } -func find(ctx *findContext, fileContent contentMessage) { +func find(ctxCtx context.Context, ctx *findContext, fileContent contentMessage) { // Match the incoming content, didn't match return. if !matchFind(ctx, fileContent) { return @@ -228,27 +229,27 @@ func find(ctx *findContext, fileContent contentMessage) { // proceed to either exec, format the output string. if ctx.execCmd != "" { - execFind(stringsReplace(ctx.execCmd, fileContent)) + execFind(stringsReplace(ctxCtx, ctx.execCmd, fileContent)) return } if ctx.printFmt != "" { - fileContent.Key = stringsReplace(ctx.printFmt, fileContent) + fileContent.Key = stringsReplace(ctxCtx, ctx.printFmt, fileContent) } printMsg(findMessage{fileContent}) } // doFind - find is main function body which interprets and executes // all the input parameters. -func doFind(ctx *findContext) error { +func doFind(ctxCtx context.Context, ctx *findContext) error { // If watch is enabled we will wait on the prefix perpetually // for all I/O events until canceled by user, if watch is not enabled // following defer is a no-op. - defer watchFind(ctx) + defer watchFind(ctxCtx, ctx) var prevKeyName string // iterate over all content which is within the given directory - for content := range ctx.clnt.List(true, false, false, DirNone) { + for content := range ctx.clnt.List(globalContext, true, false, false, DirNone) { if content.Err != nil { switch content.Err.ToGoError().(type) { // handle this specifically for filesystem related errors. @@ -288,11 +289,11 @@ func doFind(ctx *findContext) error { // proceed to either exec, format the output string. if ctx.execCmd != "" { - execFind(stringsReplace(ctx.execCmd, fileContent)) + execFind(stringsReplace(ctxCtx, ctx.execCmd, fileContent)) continue } if ctx.printFmt != "" { - fileContent.Key = stringsReplace(ctx.printFmt, fileContent) + fileContent.Key = stringsReplace(ctxCtx, ctx.printFmt, fileContent) } printMsg(findMessage{fileContent}) @@ -305,7 +306,7 @@ func doFind(ctx *findContext) error { // stringsReplace - formats the string to remove {} and replace each // with the appropriate argument -func stringsReplace(args string, fileContent contentMessage) string { +func stringsReplace(ctx context.Context, args string, fileContent contentMessage) string { // replace all instances of {} str := args if strings.Contains(str, "{}") { @@ -359,12 +360,12 @@ func stringsReplace(args string, fileContent contentMessage) string { // replace all instances of {url} if strings.Contains(str, "{url}") { - str = strings.Replace(str, "{url}", getShareURL(fileContent.Key), -1) + str = strings.Replace(str, "{url}", getShareURL(ctx, fileContent.Key), -1) } // replace all instances of {"url"} if strings.Contains(str, `{"url"}`) { - str = strings.Replace(str, `{"url"}`, strconv.Quote(getShareURL(fileContent.Key)), -1) + str = strings.Replace(str, `{"url"}`, strconv.Quote(getShareURL(ctx, fileContent.Key)), -1) } return str @@ -414,14 +415,14 @@ var defaultSevenDays = time.Duration(604800) * time.Second // getShareURL is used in conjunction with the {url} substitution // argument to generate and return presigned URLs, returns error if any. -func getShareURL(path string) string { +func getShareURL(ctx context.Context, path string) string { targetAlias, targetURLFull, _, err := expandAlias(path) fatalIf(err.Trace(path), "Unable to expand alias.") clnt, err := newClientFromAlias(targetAlias, targetURLFull) fatalIf(err.Trace(targetAlias, targetURLFull), "Unable to initialize client instance from alias.") - content, err := clnt.Stat(false, false, nil) + content, err := clnt.Stat(ctx, false, false, nil) fatalIf(err.Trace(targetURLFull, targetAlias), "Unable to lookup file/object.") // Skip if its a directory. @@ -434,7 +435,7 @@ func getShareURL(path string) string { fatalIf(err.Trace(targetAlias, objectURL), "Unable to initialize new client from alias.") // Set default expiry for each url (point of no longer valid), to be 7 days - shareURL, err := newClnt.ShareDownload(defaultSevenDays) + shareURL, err := newClnt.ShareDownload(ctx, defaultSevenDays) fatalIf(err.Trace(targetAlias, objectURL), "Unable to generate share url.") return shareURL diff --git a/cmd/find_test.go b/cmd/find_test.go index f2b30b1d..1f350177 100644 --- a/cmd/find_test.go +++ b/cmd/find_test.go @@ -17,6 +17,7 @@ package cmd import ( + "context" "os/exec" "strings" "testing" @@ -410,7 +411,7 @@ func TestStringReplace(t *testing.T) { }, } for i, testCase := range testCases { - gotStr := stringsReplace(testCase.str, testCase.content) + gotStr := stringsReplace(context.Background(), testCase.str, testCase.content) if gotStr != testCase.expectedStr { t.Errorf("Test %d: Expected %s, got %s", i+1, testCase.expectedStr, gotStr) } diff --git a/cmd/head-main.go b/cmd/head-main.go index 06c204cc..56843900 100644 --- a/cmd/head-main.go +++ b/cmd/head-main.go @@ -20,6 +20,7 @@ import ( "bufio" "compress/bzip2" "compress/gzip" + "context" "io" "io/ioutil" "os" @@ -84,7 +85,7 @@ func headURL(sourceURL string, encKeyDB map[string][]prefixSSEPair, nlines int64 default: var err *probe.Error var metadata map[string]string - if reader, metadata, err = getSourceStreamMetadataFromURL(sourceURL, encKeyDB); err != nil { + if reader, metadata, err = getSourceStreamMetadataFromURL(context.Background(), sourceURL, encKeyDB); err != nil { return err.Trace(sourceURL) } ctype := metadata["Content-Type"] diff --git a/cmd/ilm-add.go b/cmd/ilm-add.go index e1a1f8ac..d872d683 100644 --- a/cmd/ilm-add.go +++ b/cmd/ilm-add.go @@ -17,6 +17,8 @@ package cmd import ( + "context" + "github.com/minio/cli" "github.com/minio/mc/cmd/ilm" json "github.com/minio/mc/pkg/colorjson" @@ -129,30 +131,33 @@ func checkILMAddSyntax(ctx *cli.Context) { } // Calls SetBucketLifecycle with the XML representation of lifecycleConfiguration type. -func mainILMAdd(ctx *cli.Context) error { - checkILMAddSyntax(ctx) +func mainILMAdd(cliCtx *cli.Context) error { + ctx, cancelILMAdd := context.WithCancel(globalContext) + defer cancelILMAdd() + + checkILMAddSyntax(cliCtx) setILMDisplayColorScheme() - args := ctx.Args() + args := cliCtx.Args() urlStr := args.Get(0) client, err := newClient(urlStr) fatalIf(err.Trace(urlStr), "Unable to initialize client for "+urlStr) // Configuration that is already set. - lfcCfg, err := client.GetLifecycle() + lfcCfg, err := client.GetLifecycle(ctx) fatalIf(err.Trace(args...), "Unable to fetch lifecycle rules for "+urlStr) // Configuration that needs to be set is returned by ilm.GetILMConfigToSet. // A new rule is added or the rule (if existing) is replaced - lfcCfg, err = ilm.ApplyNewILMConfig(ctx, lfcCfg) + lfcCfg, err = ilm.ApplyNewILMConfig(cliCtx, lfcCfg) fatalIf(err.Trace(args...), "Unable to generate new lifecyle rules for the input") - fatalIf(client.SetLifecycle(lfcCfg).Trace(urlStr), "Unable to set new lifecycle rules") + fatalIf(client.SetLifecycle(ctx, lfcCfg).Trace(urlStr), "Unable to set new lifecycle rules") printMsg(ilmAddMessage{ Status: "success", Target: urlStr, - ID: ctx.String("id"), + ID: cliCtx.String("id"), }) return nil diff --git a/cmd/ilm-export.go b/cmd/ilm-export.go index b881f70d..3dfd9a9d 100644 --- a/cmd/ilm-export.go +++ b/cmd/ilm-export.go @@ -17,6 +17,7 @@ package cmd import ( + "context" "errors" "github.com/minio/cli" @@ -76,17 +77,20 @@ func checkILMExportSyntax(ctx *cli.Context) { } } -func mainILMExport(ctx *cli.Context) error { - checkILMExportSyntax(ctx) +func mainILMExport(cliCtx *cli.Context) error { + ctx, cancelILMExport := context.WithCancel(globalContext) + defer cancelILMExport() + + checkILMExportSyntax(cliCtx) setILMDisplayColorScheme() - args := ctx.Args() + args := cliCtx.Args() urlStr := args.Get(0) client, err := newClient(urlStr) fatalIf(err.Trace(args...), "Unable to initialize client for "+urlStr+".") - ilmCfg, err := client.GetLifecycle() + ilmCfg, err := client.GetLifecycle(ctx) fatalIf(err.Trace(args...), "Unable to get lifecycle configuration") if len(ilmCfg.Rules) == 0 { fatalIf(probe.NewError(errors.New("lifecycle configuration not set")).Trace(urlStr), diff --git a/cmd/ilm-import.go b/cmd/ilm-import.go index bdbd993f..e1c2cea6 100644 --- a/cmd/ilm-import.go +++ b/cmd/ilm-import.go @@ -17,6 +17,7 @@ package cmd import ( + "context" "os" "github.com/minio/cli" @@ -84,11 +85,14 @@ func checkILMImportSyntax(ctx *cli.Context) { } } -func mainILMImport(ctx *cli.Context) error { - checkILMImportSyntax(ctx) +func mainILMImport(cliCtx *cli.Context) error { + ctx, cancelILMImport := context.WithCancel(globalContext) + defer cancelILMImport() + + checkILMImportSyntax(cliCtx) setILMDisplayColorScheme() - args := ctx.Args() + args := cliCtx.Args() urlStr := args.Get(0) client, err := newClient(urlStr) @@ -97,7 +101,7 @@ func mainILMImport(ctx *cli.Context) error { ilmCfg, err := readILMConfig() fatalIf(err.Trace(args...), "Unable to read ILM configuration") - fatalIf(client.SetLifecycle(ilmCfg).Trace(urlStr), "Unable to set new lifecycle rules") + fatalIf(client.SetLifecycle(ctx, ilmCfg).Trace(urlStr), "Unable to set new lifecycle rules") printMsg(ilmImportMessage{ Status: "success", diff --git a/cmd/ilm-list.go b/cmd/ilm-list.go index 18ed6318..31783739 100644 --- a/cmd/ilm-list.go +++ b/cmd/ilm-list.go @@ -18,6 +18,7 @@ package cmd import ( "bytes" + "context" "errors" "strconv" "strings" @@ -253,17 +254,20 @@ func getILMRowsWithTags(tbl *PrettyTable, cellDataWithTags *[][]string, newRows return rows } -func mainILMList(ctx *cli.Context) error { - checkILMListSyntax(ctx) +func mainILMList(cliCtx *cli.Context) error { + ctx, cancelILMList := context.WithCancel(globalContext) + defer cancelILMList() + + checkILMListSyntax(cliCtx) setILMDisplayColorScheme() - args := ctx.Args() + args := cliCtx.Args() urlStr := args.Get(0) client, err := newClient(urlStr) fatalIf(err.Trace(urlStr), "Unable to initialize client for "+urlStr) - ilmCfg, err := client.GetLifecycle() + ilmCfg, err := client.GetLifecycle(ctx) fatalIf(err.Trace(args...), "Unable to get lifecycle") if len(ilmCfg.Rules) == 0 { @@ -274,7 +278,7 @@ func mainILMList(ctx *cli.Context) error { printMsg(ilmListMessage{ Status: "success", Target: urlStr, - Context: ctx, + Context: cliCtx, ILMConfig: ilmCfg, }) diff --git a/cmd/ilm-remove.go b/cmd/ilm-remove.go index aad33c56..db0fc039 100644 --- a/cmd/ilm-remove.go +++ b/cmd/ilm-remove.go @@ -17,6 +17,8 @@ package cmd import ( + "context" + "github.com/minio/cli" "github.com/minio/mc/cmd/ilm" json "github.com/minio/mc/pkg/colorjson" @@ -112,33 +114,36 @@ func checkILMRemoveSyntax(ctx *cli.Context) { } } -func mainILMRemove(ctx *cli.Context) error { - checkILMRemoveSyntax(ctx) +func mainILMRemove(cliCtx *cli.Context) error { + ctx, cancelILMImport := context.WithCancel(globalContext) + defer cancelILMImport() + + checkILMRemoveSyntax(cliCtx) setILMDisplayColorScheme() - args := ctx.Args() + args := cliCtx.Args() urlStr := args.Get(0) client, err := newClient(urlStr) fatalIf(err.Trace(args...), "Unable to initialize client for "+urlStr+".") - ilmCfg, err := client.GetLifecycle() + ilmCfg, err := client.GetLifecycle(ctx) fatalIf(err.Trace(urlStr), "Unable to fetch lifecycle rules") - ilmAll := ctx.Bool("all") - ilmForce := ctx.Bool("force") + ilmAll := cliCtx.Bool("all") + ilmForce := cliCtx.Bool("force") if ilmAll && ilmForce { ilmCfg.Rules = nil // Remove all rules } else { - ilmCfg, err = ilm.RemoveILMRule(ilmCfg, ctx.String("id")) - fatalIf(err.Trace(urlStr, ctx.String("id")), "Unable to remove rule by id") + ilmCfg, err = ilm.RemoveILMRule(ilmCfg, cliCtx.String("id")) + fatalIf(err.Trace(urlStr, cliCtx.String("id")), "Unable to remove rule by id") } - fatalIf(client.SetLifecycle(ilmCfg).Trace(urlStr), "Unable to set lifecycle rules") + fatalIf(client.SetLifecycle(ctx, ilmCfg).Trace(urlStr), "Unable to set lifecycle rules") printMsg(ilmRmMessage{ Status: "success", - ID: ctx.String("id"), + ID: cliCtx.String("id"), All: ilmAll, Target: urlStr, }) diff --git a/cmd/legalhold-main.go b/cmd/legalhold-main.go index f591ffce..ebd6a5db 100644 --- a/cmd/legalhold-main.go +++ b/cmd/legalhold-main.go @@ -17,6 +17,7 @@ package cmd import ( + "context" "encoding/json" "fmt" "strings" @@ -86,12 +87,15 @@ func (l legalHoldCmdMessage) JSON() string { // setRetention - Set Retention for all objects within a given prefix. func setLegalHold(urlStr string, lhold minio.LegalHoldStatus, isRecursive bool) error { + ctx, cancelLegalHold := context.WithCancel(globalContext) + defer cancelLegalHold() + clnt, err := newClient(urlStr) if err != nil { fatalIf(err.Trace(), "Cannot parse the provided url.") } if !isRecursive { - err = clnt.PutObjectLegalHold(lhold) + err = clnt.PutObjectLegalHold(ctx, lhold) if err != nil { errorIf(err.Trace(urlStr), "Failed to set legal hold on `"+urlStr+"` successfully") } else { @@ -107,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(isRecursive, false, false, DirNone) { + for content := range clnt.List(ctx, isRecursive, false, false, DirNone) { if content.Err != nil { errorIf(content.Err.Trace(clnt.GetURL().String()), "Unable to list folder.") cErr = exitStatus(globalErrorExitStatus) // Set the exit status. @@ -119,7 +123,7 @@ func setLegalHold(urlStr string, lhold minio.LegalHoldStatus, isRecursive bool) errorIf(content.Err.Trace(clnt.GetURL().String()), "Invalid URL") continue } - probeErr := newClnt.PutObjectLegalHold(lhold) + probeErr := newClnt.PutObjectLegalHold(ctx, lhold) if probeErr != nil { errorsFound = true errorIf(probeErr.Trace(content.URL.Path), "Failed to set legal hold on `"+content.URL.Path+"` successfully") diff --git a/cmd/lock-main.go b/cmd/lock-main.go index 0311029e..b006eb96 100644 --- a/cmd/lock-main.go +++ b/cmd/lock-main.go @@ -17,6 +17,7 @@ package cmd import ( + "context" "fmt" "strconv" "strings" @@ -99,11 +100,14 @@ func lock(urlStr string, mode minio.RetentionMode, validity uint64, unit minio.V fatalIf(err.Trace(), "Cannot parse the provided url.") } + ctx, cancelLock := context.WithCancel(globalContext) + defer cancelLock() + if clearLock || mode != "" { - err = client.SetObjectLockConfig(mode, validity, unit) + err = client.SetObjectLockConfig(ctx, mode, validity, unit) fatalIf(err, "Cannot enable object lock configuration on the specified bucket.") } else { - mode, validity, unit, err = client.GetObjectLockConfig() + mode, validity, unit, err = client.GetObjectLockConfig(ctx) fatalIf(err, "Cannot get object lock configuration on the specified bucket.") } diff --git a/cmd/ls-main.go b/cmd/ls-main.go index 53039671..200b4874 100644 --- a/cmd/ls-main.go +++ b/cmd/ls-main.go @@ -17,6 +17,7 @@ package cmd import ( + "context" "strings" "github.com/fatih/color" @@ -76,9 +77,9 @@ EXAMPLES: } // checkListSyntax - validate all the passed arguments -func checkListSyntax(ctx *cli.Context) { - args := ctx.Args() - if !ctx.Args().Present() { +func checkListSyntax(ctx context.Context, cliCtx *cli.Context) { + args := cliCtx.Args() + if !cliCtx.Args().Present() { args = []string{"."} } for _, arg := range args { @@ -87,11 +88,11 @@ func checkListSyntax(ctx *cli.Context) { } } // extract URLs. - URLs := ctx.Args() - isIncomplete := ctx.Bool("incomplete") + URLs := cliCtx.Args() + isIncomplete := cliCtx.Bool("incomplete") for _, url := range URLs { - _, _, err := url2Stat(url, false, nil) + _, _, err := url2Stat(ctx, url, false, nil) if err != nil && !isURLPrefixExists(url, isIncomplete) { // Bucket name empty is a valid error for 'ls myminio', // treat it as such. @@ -106,23 +107,26 @@ func checkListSyntax(ctx *cli.Context) { } // mainList - is a handler for mc ls command -func mainList(ctx *cli.Context) error { +func mainList(cliCtx *cli.Context) error { + ctx, cancelList := context.WithCancel(globalContext) + defer cancelList() + // Additional command specific theme customization. console.SetColor("File", color.New(color.Bold)) 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' cli arguments. - checkListSyntax(ctx) + // check 'ls' cliCtx arguments. + checkListSyntax(ctx, cliCtx) // Set command flags from context. - isRecursive := ctx.Bool("recursive") - isIncomplete := ctx.Bool("incomplete") + isRecursive := cliCtx.Bool("recursive") + isIncomplete := cliCtx.Bool("incomplete") - args := ctx.Args() + args := cliCtx.Args() // mimic operating system tool behavior. - if !ctx.Args().Present() { + if !cliCtx.Args().Present() { args = []string{"."} } @@ -130,10 +134,9 @@ func mainList(ctx *cli.Context) error { for _, targetURL := range args { clnt, err := newClient(targetURL) fatalIf(err.Trace(targetURL), "Unable to initialize target `"+targetURL+"`.") - if !strings.HasSuffix(targetURL, string(clnt.GetURL().Separator)) { var st *ClientContent - st, err = clnt.Stat(isIncomplete, false, nil) + st, err = clnt.Stat(ctx, isIncomplete, false, nil) if st != nil && err == nil && st.Type.IsDir() { targetURL = targetURL + string(clnt.GetURL().Separator) clnt, err = newClient(targetURL) @@ -141,7 +144,7 @@ func mainList(ctx *cli.Context) error { } } - if e := doList(clnt, isRecursive, isIncomplete); e != nil { + if e := doList(ctx, clnt, isRecursive, isIncomplete); e != nil { cErr = e } } diff --git a/cmd/ls.go b/cmd/ls.go index c48fd9f5..68bde765 100644 --- a/cmd/ls.go +++ b/cmd/ls.go @@ -17,6 +17,7 @@ package cmd import ( + "context" "fmt" "path/filepath" "runtime" @@ -106,14 +107,15 @@ func getKey(c *ClientContent) string { } // doList - list all entities inside a folder. -func doList(clnt Client, isRecursive, isIncomplete bool) error { +func doList(ctx context.Context, clnt Client, isRecursive, isIncomplete bool) error { prefixPath := clnt.GetURL().Path separator := string(clnt.GetURL().Separator) if !strings.HasSuffix(prefixPath, separator) { prefixPath = prefixPath[:strings.LastIndex(prefixPath, separator)+1] } + var cErr error - for content := range clnt.List(isRecursive, isIncomplete, false, DirNone) { + for content := range clnt.List(ctx, isRecursive, isIncomplete, false, DirNone) { if content.Err != nil { switch content.Err.ToGoError().(type) { // handle this specifically for filesystem related errors. diff --git a/cmd/main.go b/cmd/main.go index a6c646da..aff8aaad 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -73,6 +73,7 @@ VERSION: // Main starts mc application func Main(args []string) { + if len(args) > 1 { switch args[1] { case "mc", filepath.Base(args[0]): diff --git a/cmd/mb-main.go b/cmd/mb-main.go index 2212dbdd..cb1b0b28 100644 --- a/cmd/mb-main.go +++ b/cmd/mb-main.go @@ -17,6 +17,8 @@ package cmd import ( + "context" + "github.com/fatih/color" "github.com/minio/cli" json "github.com/minio/mc/pkg/colorjson" @@ -103,28 +105,28 @@ func (s makeBucketMessage) JSON() string { } // Validate command line arguments. -func checkMakeBucketSyntax(ctx *cli.Context) { - if !ctx.Args().Present() { - cli.ShowCommandHelpAndExit(ctx, "mb", 1) // last argument is exit code +func checkMakeBucketSyntax(cliCtx *cli.Context) { + if !cliCtx.Args().Present() { + cli.ShowCommandHelpAndExit(cliCtx, "mb", 1) // last argument is exit code } } // mainMakeBucket is entry point for mb command. -func mainMakeBucket(ctx *cli.Context) error { +func mainMakeBucket(cli *cli.Context) error { // check 'mb' cli arguments. - checkMakeBucketSyntax(ctx) + checkMakeBucketSyntax(cli) // Additional command speific theme customization. console.SetColor("MakeBucket", color.New(color.FgGreen, color.Bold)) // Save region. - region := ctx.String("region") - ignoreExisting := ctx.Bool("p") - withLock := ctx.Bool("l") + region := cli.String("region") + ignoreExisting := cli.Bool("p") + withLock := cli.Bool("l") var cErr error - for _, targetURL := range ctx.Args() { + for _, targetURL := range cli.Args() { // Instantiate client for URL. clnt, err := newClient(targetURL) if err != nil { @@ -133,8 +135,11 @@ func mainMakeBucket(ctx *cli.Context) error { continue } + ctx, cancelMakeBucket := context.WithCancel(globalContext) + defer cancelMakeBucket() + // Make bucket. - err = clnt.MakeBucket(region, ignoreExisting, withLock) + err = clnt.MakeBucket(ctx, region, ignoreExisting, withLock) if err != nil { switch err.ToGoError().(type) { case BucketNameEmpty: diff --git a/cmd/mirror-main.go b/cmd/mirror-main.go index 056ffed1..38e0e30b 100644 --- a/cmd/mirror-main.go +++ b/cmd/mirror-main.go @@ -251,7 +251,7 @@ func (m mirrorMessage) JSON() string { } // doRemove - removes files on target. -func (mj *mirrorJob) doRemove(sURLs URLs) URLs { +func (mj *mirrorJob) doRemove(ctx context.Context, sURLs URLs) URLs { if mj.isFake { return sURLs.WithError(nil) } @@ -267,7 +267,7 @@ func (mj *mirrorJob) doRemove(sURLs URLs) URLs { contentCh <- &ClientContent{URL: *newClientURL(sURLs.TargetContent.URL.Path)} close(contentCh) isRemoveBucket := false - errorCh := clnt.Remove(false, isRemoveBucket, false, contentCh) + errorCh := clnt.Remove(ctx, false, isRemoveBucket, false, contentCh) for pErr := range errorCh { if pErr != nil { switch pErr.ToGoError().(type) { @@ -291,7 +291,7 @@ func (mj *mirrorJob) doMirrorWatch(ctx context.Context, targetPath string, tgtSS // cannot create targetclient return sURLs.WithError(err) } - _, err = targetClient.Stat(false, false, tgtSSE) + _, err = targetClient.Stat(ctx, false, false, tgtSSE) if err == nil { if !sURLs.SourceContent.RetentionEnabled && !sURLs.SourceContent.LegalHoldEnabled { return sURLs.WithError(probe.NewError(ObjectAlreadyExists{})) @@ -501,7 +501,7 @@ func (mj *mirrorJob) watchMirrorEvents(ctx context.Context, events []EventInfo) mirrorURL.TotalSize = mj.status.Get() if mirrorURL.TargetContent != nil && (mj.isRemove || mj.activeActive) { mj.queueCh <- func() URLs { - return mj.doRemove(mirrorURL) + return mj.doRemove(ctx, mirrorURL) } } } @@ -541,8 +541,8 @@ func (mj *mirrorJob) watchMirror(ctx context.Context, stopParallel func()) { } } -func (mj *mirrorJob) watchURL(sourceClient Client) *probe.Error { - return mj.watcher.Join(sourceClient, true) +func (mj *mirrorJob) watchURL(ctx context.Context, sourceClient Client) *probe.Error { + return mj.watcher.Join(ctx, sourceClient, true) } // Fetch urls that need to be mirrored @@ -592,7 +592,7 @@ func (mj *mirrorJob) startMirror(ctx context.Context, cancelMirror context.Cance } } else if sURLs.TargetContent != nil && mj.isRemove { mj.queueCh <- func() URLs { - return mj.doRemove(sURLs) + return mj.doRemove(ctx, sURLs) } } case <-globalContext.Done(): @@ -692,8 +692,8 @@ func newMirrorJob(srcURL, dstURL string, isFake, isRemove, isOverwrite, isWatch, } // copyBucketPolicies - copy policies from source to dest -func copyBucketPolicies(srcClt, dstClt Client, isOverwrite bool) *probe.Error { - rules, err := srcClt.GetAccessRules() +func copyBucketPolicies(ctx context.Context, srcClt, dstClt Client, isOverwrite bool) *probe.Error { + rules, err := srcClt.GetAccessRules(ctx) if err != nil { switch err.ToGoError().(type) { case APINotImplemented: @@ -703,14 +703,14 @@ func copyBucketPolicies(srcClt, dstClt Client, isOverwrite bool) *probe.Error { } // Set found rules to target bucket if permitted for _, r := range rules { - originalRule, _, err := dstClt.GetAccess() + originalRule, _, err := dstClt.GetAccess(ctx) if err != nil { return err } // Set rule only if it doesn't exist in the target bucket // or force flag is activated if originalRule == "none" || isOverwrite { - err = dstClt.SetAccess(r, false) + err = dstClt.SetAccess(ctx, r, false) if err != nil { return err } @@ -743,20 +743,20 @@ func getEventPathURLWin(srcURL, eventPath string) string { } // runMirror - mirrors all buckets to another S3 server -func runMirror(srcURL, dstURL string, ctx *cli.Context, encKeyDB map[string][]prefixSSEPair) bool { +func runMirror(srcURL, dstURL string, cli *cli.Context, encKeyDB map[string][]prefixSSEPair) bool { // This is kept for backward compatibility, `--force` means // --overwrite. - isOverwrite := ctx.Bool("force") + isOverwrite := cli.Bool("force") if !isOverwrite { - isOverwrite = ctx.Bool("overwrite") + isOverwrite = cli.Bool("overwrite") } // Parse metadata. userMetaMap := make(map[string]string) - if ctx.String("attr") != "" { + if cli.String("attr") != "" { var err *probe.Error - userMetaMap, err = getMetaDataEntry(ctx.String("attr")) - fatalIf(err, "Unable to parse attribute %v", ctx.String("attr")) + userMetaMap, err = getMetaDataEntry(cli.String("attr")) + fatalIf(err, "Unable to parse attribute %v", cli.String("attr")) } srcClt, err := newClient(srcURL) @@ -781,20 +781,20 @@ func runMirror(srcURL, dstURL string, ctx *cli.Context, encKeyDB map[string][]pr // Create a new mirror job and execute it mj := newMirrorJob(srcURL, dstURL, - ctx.Bool("fake"), - ctx.Bool("remove"), + cli.Bool("fake"), + cli.Bool("remove"), isOverwrite, - ctx.Bool("watch"), - ctx.Bool("a"), - ctx.Bool("multi-master") || ctx.Bool("active-active"), - ctx.StringSlice("exclude"), - ctx.String("older-than"), - ctx.String("newer-than"), - ctx.String("storage-class"), + cli.Bool("watch"), + cli.Bool("a"), + cli.Bool("multi-master") || cli.Bool("active-active"), + cli.StringSlice("exclude"), + cli.String("older-than"), + cli.String("newer-than"), + cli.String("storage-class"), userMetaMap, encKeyDB, - ctx.Bool("md5"), - ctx.Bool("disable-multipart"), + cli.Bool("md5"), + cli.Bool("disable-multipart"), ) go func() { @@ -802,6 +802,9 @@ func runMirror(srcURL, dstURL string, ctx *cli.Context, encKeyDB map[string][]pr os.Exit(globalErrorExitStatus) }() + ctx, cancelMirror := context.WithCancel(globalContext) + defer cancelMirror() + if mirrorAllBuckets { // Synchronize buckets using dirDifference function for d := range dirDifference(srcClt, dstClt, srcURL, dstURL) { @@ -826,28 +829,28 @@ func runMirror(srcURL, dstURL string, ctx *cli.Context, encKeyDB map[string][]pr if d.Diff == differInFirst { withLock := false - mode, validity, unit, err := newSrcClt.GetObjectLockConfig() + mode, validity, unit, err := newSrcClt.GetObjectLockConfig(ctx) if err == nil { withLock = true } // Bucket only exists in the source, create the same bucket in the destination - if err := newDstClt.MakeBucket(ctx.String("region"), false, withLock); err != nil { + if err := newDstClt.MakeBucket(ctx, cli.String("region"), false, withLock); err != nil { errorIf(err, "Unable to create bucket at `"+newTgtURL+"`.") continue } // object lock configuration set on bucket if mode != "" { - errorIf(newDstClt.SetObjectLockConfig(mode, validity, unit), + errorIf(newDstClt.SetObjectLockConfig(ctx, mode, validity, unit), "Unable to set object lock config in `"+newTgtURL+"`.") } - errorIf(copyBucketPolicies(newSrcClt, newDstClt, isOverwrite), + errorIf(copyBucketPolicies(ctx, newSrcClt, newDstClt, isOverwrite), "Unable to copy bucket policies to `"+newDstClt.GetURL().String()+"`.") } if mj.isWatch { // monitor mode will watch the source folders for changes, // and queue them for copying. - if err := mj.watchURL(newSrcClt); err != nil { + if err := mj.watchURL(ctx, newSrcClt); err != nil { if mj.activeActive { errorIf(err, "Failed to start monitoring.") return true @@ -856,9 +859,9 @@ func runMirror(srcURL, dstURL string, ctx *cli.Context, encKeyDB map[string][]pr } } } - } else if _, err := dstClt.Stat(false, false, nil); err != nil { + } else if _, err := dstClt.Stat(ctx, false, false, nil); err != nil { withLock := false - mode, validity, unit, err := srcClt.GetObjectLockConfig() + mode, validity, unit, err := srcClt.GetObjectLockConfig(ctx) if err == nil { withLock = true } @@ -866,26 +869,26 @@ func runMirror(srcURL, dstURL string, ctx *cli.Context, encKeyDB map[string][]pr // Create bucket if it doesn't exist at destination. // ignore if already exists. if mj.activeActive { - err = dstClt.MakeBucket(ctx.String("region"), true, withLock) + err = dstClt.MakeBucket(ctx, cli.String("region"), true, withLock) errorIf(err, "Unable to create bucket at `"+dstURL+"`.") if err != nil { return true } } else { - mj.status.fatalIf(dstClt.MakeBucket(ctx.String("region"), true, withLock), + mj.status.fatalIf(dstClt.MakeBucket(ctx, cli.String("region"), true, withLock), "Unable to create bucket at `"+dstURL+"`.") } // object lock configuration set on bucket if mode != "" { - err = dstClt.SetObjectLockConfig(mode, validity, unit) + err = dstClt.SetObjectLockConfig(ctx, mode, validity, unit) errorIf(err, "Unable to set object lock config in `"+dstURL+"`.") if err != nil && mj.activeActive { return true } } - err = copyBucketPolicies(srcClt, dstClt, isOverwrite) + err = copyBucketPolicies(ctx, srcClt, dstClt, isOverwrite) errorIf(err, "Unable to copy bucket policies to `"+dstClt.GetURL().String()+"`.") if err != nil && mj.activeActive { return true @@ -895,7 +898,7 @@ func runMirror(srcURL, dstURL string, ctx *cli.Context, encKeyDB map[string][]pr if !mirrorAllBuckets && mj.isWatch { // monitor mode will watch the source folders for changes, // and queue them for copying. - if err := mj.watchURL(srcClt); err != nil { + if err := mj.watchURL(ctx, srcClt); err != nil { if mj.activeActive { errorIf(err, "Failed to start monitoring.") return true @@ -904,26 +907,26 @@ func runMirror(srcURL, dstURL string, ctx *cli.Context, encKeyDB map[string][]pr } } - ctxt, cancelMirror := context.WithCancel(context.Background()) - defer cancelMirror() - // Start mirroring job - return mj.mirror(ctxt, cancelMirror) + return mj.mirror(ctx, cancelMirror) } // Main entry point for mirror command. -func mainMirror(ctx *cli.Context) error { +func mainMirror(cliCtx *cli.Context) error { + ctx, cancelMirror := context.WithCancel(globalContext) + defer cancelMirror() + // Parse encryption keys per command. - encKeyDB, err := getEncKeys(ctx) + encKeyDB, err := getEncKeys(cliCtx) fatalIf(err, "Unable to parse encryption keys.") // check 'mirror' cli arguments. - checkMirrorSyntax(ctx, encKeyDB) + checkMirrorSyntax(ctx, cliCtx, encKeyDB) // Additional command specific theme customization. console.SetColor("Mirror", color.New(color.FgGreen, color.Bold)) - args := ctx.Args() + args := cliCtx.Args() srcURL := args[0] tgtURL := args[1] @@ -937,14 +940,14 @@ func mainMirror(ctx *cli.Context) error { } } - if ctx.Bool("multi-master") || ctx.Bool("active-active") { + if cliCtx.Bool("multi-master") || cliCtx.Bool("active-active") { for { - runMirror(srcURL, tgtURL, ctx, encKeyDB) + runMirror(srcURL, tgtURL, cliCtx, encKeyDB) time.Sleep(time.Second * 2) } } - if errorDetected := runMirror(srcURL, tgtURL, ctx, encKeyDB); errorDetected { + if errorDetected := runMirror(srcURL, tgtURL, cliCtx, encKeyDB); errorDetected { return exitStatus(globalErrorExitStatus) } diff --git a/cmd/mirror-url.go b/cmd/mirror-url.go index daf7603f..3b7975ce 100644 --- a/cmd/mirror-url.go +++ b/cmd/mirror-url.go @@ -17,6 +17,7 @@ package cmd import ( + "context" "fmt" "runtime" "strings" @@ -31,19 +32,19 @@ import ( // mirror(d1..., d2) -> []mirror(d1/f, d2/d1/f) // checkMirrorSyntax(URLs []string) -func checkMirrorSyntax(ctx *cli.Context, encKeyDB map[string][]prefixSSEPair) { - if len(ctx.Args()) != 2 { - cli.ShowCommandHelpAndExit(ctx, "mirror", 1) // last argument is exit code. +func checkMirrorSyntax(ctx context.Context, cliCtx *cli.Context, encKeyDB map[string][]prefixSSEPair) { + if len(cliCtx.Args()) != 2 { + cli.ShowCommandHelpAndExit(cliCtx, "mirror", 1) // last argument is exit code. } // extract URLs. - URLs := ctx.Args() + URLs := cliCtx.Args() srcURL := URLs[0] tgtURL := URLs[1] - if ctx.Bool("force") && ctx.Bool("remove") { + if cliCtx.Bool("force") && cliCtx.Bool("remove") { errorIf(errInvalidArgument().Trace(URLs...), "`--force` is deprecated please use `--overwrite` instead with `--remove` for the same functionality.") - } else if ctx.Bool("force") { + } else if cliCtx.Bool("force") { errorIf(errInvalidArgument().Trace(URLs...), "`--force` is deprecated please use `--overwrite` instead for the same functionality.") } @@ -62,15 +63,15 @@ func checkMirrorSyntax(ctx *cli.Context, encKeyDB map[string][]prefixSSEPair) { // Mirror with preserve option on windows // only works for object storage to object storage - if runtime.GOOS == "windows" && ctx.Bool("a") { + if runtime.GOOS == "windows" && cliCtx.Bool("a") { if srcClient.Type == fileSystem || destClient.Type == fileSystem { errorIf(errInvalidArgument(), "Preserve functionality on windows support object storage to object storage transfer only.") } } /****** Generic rules *******/ - if !ctx.Bool("watch") { - _, srcContent, err := url2Stat(srcURL, false, encKeyDB) + if !cliCtx.Bool("watch") { + _, srcContent, err := url2Stat(ctx, srcURL, false, encKeyDB) // incomplete uploads are not necessary for copy operation, no need to verify for them. isIncomplete := false if err != nil && !isURLPrefixExists(srcURL, isIncomplete) { diff --git a/cmd/mv-main.go b/cmd/mv-main.go index e0ae4fb4..64ad4b87 100644 --- a/cmd/mv-main.go +++ b/cmd/mv-main.go @@ -17,6 +17,7 @@ package cmd import ( + "context" "errors" "fmt" "os" @@ -181,7 +182,7 @@ func (rm *removeManager) readErrors(errorCh <-chan *probe.Error, targetURL strin }() } -func (rm *removeManager) add(targetAlias, targetURL string) { +func (rm *removeManager) add(ctx context.Context, targetAlias, targetURL string) { if atomic.LoadInt32(&rm.isClosed) != 0 { return } @@ -198,7 +199,7 @@ func (rm *removeManager) add(targetAlias, targetURL string) { } contentCh := make(chan *ClientContent) - errorCh := client.Remove(false, false, false, contentCh) + errorCh := client.Remove(ctx, false, false, false, contentCh) rm.readErrors(errorCh, targetURL) clientInfo = &removeClientInfo{ @@ -236,7 +237,7 @@ var rmManager = &removeManager{ doneCh: make(chan struct{}), } -func bgRemove(url string) { +func bgRemove(ctx context.Context, url string) { remove := func(targetAlias, targetURL string) { clnt, pErr := newClientFromAlias(targetAlias, targetURL) if pErr != nil { @@ -246,7 +247,7 @@ func bgRemove(url string) { contentCh := make(chan *ClientContent, 1) contentCh <- &ClientContent{URL: *newClientURL(targetURL)} close(contentCh) - errorCh := clnt.Remove(false, false, false, contentCh) + errorCh := clnt.Remove(ctx, false, false, false, contentCh) for pErr := range errorCh { if pErr != nil { errorIf(pErr.Trace(url), "Failed to remove `"+url+"`.") @@ -266,27 +267,30 @@ func bgRemove(url string) { return } - rmManager.add(targetAlias, targetURL) + rmManager.add(ctx, targetAlias, targetURL) } // mainMove is the entry point for mv command. -func mainMove(ctx *cli.Context) error { +func mainMove(cliCtx *cli.Context) error { + ctx, cancelMove := context.WithCancel(globalContext) + defer cancelMove() + // Parse encryption keys per command. - encKeyDB, err := getEncKeys(ctx) + encKeyDB, err := getEncKeys(cliCtx) fatalIf(err, "Unable to parse encryption keys.") // Parse metadata. userMetaMap := make(map[string]string) - if ctx.String("attr") != "" { - userMetaMap, err = getMetaDataEntry(ctx.String("attr")) - fatalIf(err, "Unable to parse attribute %v", ctx.String("attr")) + if cliCtx.String("attr") != "" { + userMetaMap, err = getMetaDataEntry(cliCtx.String("attr")) + fatalIf(err, "Unable to parse attribute %v", cliCtx.String("attr")) } // check 'copy' cli arguments. - checkCopySyntax(ctx, encKeyDB, true) + checkCopySyntax(ctx, cliCtx, encKeyDB, true) - if ctx.NArg() == 2 { - args := ctx.Args() + if cliCtx.NArg() == 2 { + args := cliCtx.Args() srcURL := args.Get(0) dstURL := args.Get(1) if srcURL == dstURL { @@ -294,14 +298,14 @@ func mainMove(ctx *cli.Context) error { } } - for _, urlStr := range ctx.Args() { + for _, urlStr := range cliCtx.Args() { client, err := newClient(urlStr) if err != nil { fatalIf(err.Trace(), "Cannot parse the provided url.") } if s3Client, ok := client.(*S3Client); ok { - if _, _, _, err = s3Client.GetObjectLockConfig(); err == nil { + if _, _, _, err = s3Client.GetObjectLockConfig(ctx); err == nil { fatalIf(probe.NewError(errors.New("")), fmt.Sprintf("Object lock configuration is enabled on the specified bucket in alias %v.", urlStr)) } } @@ -310,12 +314,12 @@ func mainMove(ctx *cli.Context) error { // Additional command speific theme customization. console.SetColor("Copy", color.New(color.FgGreen, color.Bold)) - recursive := ctx.Bool("recursive") - olderThan := ctx.String("older-than") - newerThan := ctx.String("newer-than") - storageClass := ctx.String("storage-class") + recursive := cliCtx.Bool("recursive") + olderThan := cliCtx.String("older-than") + newerThan := cliCtx.String("newer-than") + storageClass := cliCtx.String("storage-class") sseKeys := os.Getenv("MC_ENCRYPT_KEY") - if key := ctx.String("encrypt-key"); key != "" { + if key := cliCtx.String("encrypt-key"); key != "" { sseKeys = key } @@ -323,12 +327,12 @@ func mainMove(ctx *cli.Context) error { sseKeys, err = getDecodedKey(sseKeys) fatalIf(err, "Unable to parse encryption keys.") } - sse := ctx.String("encrypt") + sse := cliCtx.String("encrypt") var session *sessionV8 - if ctx.Bool("continue") { - sessionID := getHash("mv", ctx.Args()) + if cliCtx.Bool("continue") { + sessionID := getHash("mv", cliCtx.Args()) if isSessionExists(sessionID) { session, err = loadSessionV8(sessionID) fatalIf(err.Trace(sessionID), "Unable to load session.") @@ -341,13 +345,13 @@ func mainMove(ctx *cli.Context) error { session.Header.CommandStringFlags["storage-class"] = storageClass session.Header.CommandStringFlags["encrypt-key"] = sseKeys session.Header.CommandStringFlags["encrypt"] = sse - session.Header.CommandBoolFlags["session"] = ctx.Bool("continue") + session.Header.CommandBoolFlags["session"] = cliCtx.Bool("continue") - if ctx.Bool("preserve") { - session.Header.CommandBoolFlags["preserve"] = ctx.Bool("preserve") + if cliCtx.Bool("preserve") { + session.Header.CommandBoolFlags["preserve"] = cliCtx.Bool("preserve") } session.Header.UserMetaData = userMetaMap - session.Header.CommandBoolFlags["disable-multipart"] = ctx.Bool("disable-multipart") + session.Header.CommandBoolFlags["disable-multipart"] = cliCtx.Bool("disable-multipart") var e error if session.Header.RootPath, e = os.Getwd(); e != nil { @@ -356,11 +360,11 @@ func mainMove(ctx *cli.Context) error { } // extract URLs. - session.Header.CommandArgs = ctx.Args() + session.Header.CommandArgs = cliCtx.Args() } } - e := doCopySession(ctx, session, encKeyDB, true) + e := doCopySession(ctx, cancelMove, cliCtx, session, encKeyDB, true) if session != nil { session.Delete() } diff --git a/cmd/policy-main.go b/cmd/policy-main.go index b6857785..3bb02df9 100644 --- a/cmd/policy-main.go +++ b/cmd/policy-main.go @@ -18,6 +18,7 @@ package cmd import ( "bytes" + "context" "io" "net/url" "os" @@ -253,20 +254,20 @@ func accessPermToString(perm accessPerms) string { } // doSetAccess do set access. -func doSetAccess(targetURL string, targetPERMS accessPerms) *probe.Error { +func doSetAccess(ctx context.Context, targetURL string, targetPERMS accessPerms) *probe.Error { clnt, err := newClient(targetURL) if err != nil { return err.Trace(targetURL) } policy := accessPermToString(targetPERMS) - if err = clnt.SetAccess(policy, false); err != nil { + if err = clnt.SetAccess(ctx, policy, false); err != nil { return err.Trace(targetURL, string(targetPERMS)) } return nil } // doSetAccessJSON do set access JSON. -func doSetAccessJSON(targetURL string, targetPERMS accessPerms) *probe.Error { +func doSetAccessJSON(ctx context.Context, targetURL string, targetPERMS accessPerms) *probe.Error { clnt, err := newClient(targetURL) if err != nil { return err.Trace(targetURL) @@ -289,7 +290,7 @@ func doSetAccessJSON(targetURL string, targetPERMS accessPerms) *probe.Error { } configBytes := configBuf[:n] - if err = clnt.SetAccess(string(configBytes), true); err != nil { + if err = clnt.SetAccess(ctx, string(configBytes), true); err != nil { return err.Trace(targetURL, string(targetPERMS)) } return nil @@ -314,12 +315,12 @@ func stringToAccessPerm(perm string) accessPerms { } // doGetAccess do get access. -func doGetAccess(targetURL string) (perms accessPerms, policyStr string, err *probe.Error) { +func doGetAccess(ctx context.Context, targetURL string) (perms accessPerms, policyStr string, err *probe.Error) { clnt, err := newClient(targetURL) if err != nil { return "", "", err.Trace(targetURL) } - perm, policyJSON, err := clnt.GetAccess() + perm, policyJSON, err := clnt.GetAccess(ctx) if err != nil { return "", "", err.Trace(targetURL) } @@ -327,18 +328,21 @@ func doGetAccess(targetURL string) (perms accessPerms, policyStr string, err *pr } // doGetAccessRules do get access rules. -func doGetAccessRules(targetURL string) (r map[string]string, err *probe.Error) { +func doGetAccessRules(ctx context.Context, targetURL string) (r map[string]string, err *probe.Error) { clnt, err := newClient(targetURL) if err != nil { return map[string]string{}, err.Trace(targetURL) } - return clnt.GetAccessRules() + return clnt.GetAccessRules(ctx) } // Run policy list command func runPolicyListCmd(args cli.Args) { + ctx, cancelPolicyList := context.WithCancel(globalContext) + defer cancelPolicyList() + targetURL := args.First() - policies, err := doGetAccessRules(targetURL) + policies, err := doGetAccessRules(ctx, targetURL) if err != nil { switch err.ToGoError().(type) { case APINotImplemented: @@ -354,11 +358,14 @@ func runPolicyListCmd(args cli.Args) { // Run policy links command func runPolicyLinksCmd(args cli.Args, recursive bool) { + ctx, cancelPolicyLinks := context.WithCancel(globalContext) + defer cancelPolicyLinks() + // Get alias/bucket/prefix argument targetURL := args.First() // Fetch all policies associated to the passed url - policies, err := doGetAccessRules(targetURL) + policies, err := doGetAccessRules(ctx, targetURL) if err != nil { switch err.ToGoError().(type) { case APINotImplemented: @@ -394,7 +401,7 @@ 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(isRecursive, isIncomplete, false, DirFirst) { + for content := range clnt.List(globalContext, isRecursive, isIncomplete, false, DirFirst) { if content.Err != nil { errorIf(content.Err.Trace(clnt.GetURL().String()), "Unable to list folder.") continue @@ -422,15 +429,18 @@ func runPolicyLinksCmd(args cli.Args, recursive bool) { // Run policy cmd to fetch set permission func runPolicyCmd(args cli.Args) { + ctx, cancelPolicy := context.WithCancel(globalContext) + defer cancelPolicy() + var operation, policyStr string var probeErr *probe.Error perms := accessPerms(args.Get(1)) targetURL := args.Get(2) if perms.isValidAccessPERM() { - probeErr = doSetAccess(targetURL, perms) + probeErr = doSetAccess(ctx, targetURL, perms) operation = "set" } else if perms.isValidAccessFile() { - probeErr = doSetAccessJSON(targetURL, perms) + probeErr = doSetAccessJSON(ctx, targetURL, perms) operation = "set-json" } else { targetURL = args.Get(1) @@ -438,7 +448,7 @@ func runPolicyCmd(args cli.Args) { if args.First() == "get-json" { operation = "get-json" } - perms, policyStr, probeErr = doGetAccess(targetURL) + perms, policyStr, probeErr = doGetAccess(ctx, targetURL) } // Upon error exit. diff --git a/cmd/rb-main.go b/cmd/rb-main.go index 9934db40..bcb1212c 100644 --- a/cmd/rb-main.go +++ b/cmd/rb-main.go @@ -93,17 +93,17 @@ func (s removeBucketMessage) JSON() string { } // Validate command line arguments. -func checkRbSyntax(ctx *cli.Context) { - if !ctx.Args().Present() { +func checkRbSyntax(ctx context.Context, cliCtx *cli.Context) { + if !cliCtx.Args().Present() { exitCode := 1 - cli.ShowCommandHelpAndExit(ctx, "rb", exitCode) + cli.ShowCommandHelpAndExit(cliCtx, "rb", exitCode) } // Set command flags from context. - isForce := ctx.Bool("force") - isDangerous := ctx.Bool("dangerous") + isForce := cliCtx.Bool("force") + isDangerous := cliCtx.Bool("dangerous") - for _, url := range ctx.Args() { - if isNamespaceRemoval(url) { + for _, url := range cliCtx.Args() { + if isNamespaceRemoval(ctx, url) { if isForce && isDangerous { continue } @@ -114,10 +114,7 @@ func checkRbSyntax(ctx *cli.Context) { } // deletes a bucket and all its contents -func deleteBucket(url string) *probe.Error { - ctx, cancelCopy := context.WithCancel(globalContext) - defer cancelCopy() - +func deleteBucket(ctx context.Context, url string) *probe.Error { targetAlias, targetURL, _ := mustExpandAlias(url) clnt, pErr := newClientFromAlias(targetAlias, targetURL) if pErr != nil { @@ -126,11 +123,11 @@ func deleteBucket(url string) *probe.Error { var isIncomplete bool isRemoveBucket := true contentCh := make(chan *ClientContent) - errorCh := clnt.Remove(isIncomplete, isRemoveBucket, false, contentCh) + errorCh := clnt.Remove(ctx, isIncomplete, isRemoveBucket, false, contentCh) go func() { defer close(contentCh) - for content := range clnt.List(true, false, false, DirLast) { + for content := range clnt.List(ctx, true, false, false, DirLast) { if content.Err != nil { contentCh <- content continue @@ -175,12 +172,12 @@ func deleteBucket(url string) *probe.Error { // isNamespaceRemoval returns true if alias // is not qualified by bucket -func isNamespaceRemoval(url string) bool { +func isNamespaceRemoval(ctx context.Context, url string) bool { // clean path for aliases like s3/. //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(url, nil) { + if !isAliasURLDir(ctx, url, nil) { _, path := url2Alias(url) return (path == "") } @@ -188,16 +185,19 @@ func isNamespaceRemoval(url string) bool { } // mainRemoveBucket is entry point for rb command. -func mainRemoveBucket(ctx *cli.Context) error { +func mainRemoveBucket(cliCtx *cli.Context) error { + ctx, cancelRemoveBucket := context.WithCancel(globalContext) + defer cancelRemoveBucket() + // check 'rb' cli arguments. - checkRbSyntax(ctx) - isForce := ctx.Bool("force") + checkRbSyntax(ctx, cliCtx) + isForce := cliCtx.Bool("force") // Additional command specific theme customization. console.SetColor("RemoveBucket", color.New(color.FgGreen, color.Bold)) var cErr error - for _, targetURL := range ctx.Args() { + for _, targetURL := range cliCtx.Args() { // Instantiate client for URL. clnt, err := newClient(targetURL) if err != nil { @@ -205,7 +205,7 @@ func mainRemoveBucket(ctx *cli.Context) error { cErr = exitStatus(globalErrorExitStatus) continue } - _, err = clnt.Stat(false, false, nil) + _, err = clnt.Stat(ctx, false, false, nil) if err != nil { switch err.ToGoError().(type) { case BucketNameEmpty: @@ -218,7 +218,7 @@ func mainRemoveBucket(ctx *cli.Context) error { } isEmpty := true - for range clnt.List(true, false, false, DirNone) { + for range clnt.List(ctx, true, false, false, DirNone) { isEmpty = false break } @@ -227,10 +227,10 @@ func mainRemoveBucket(ctx *cli.Context) error { fatalIf(errDummy().Trace(), "`"+targetURL+"` is not empty. Retry this command with ‘--force’ flag if you want to remove `"+targetURL+"` and all its contents") } - e := deleteBucket(targetURL) + e := deleteBucket(ctx, targetURL) fatalIf(e.Trace(targetURL), "Failed to remove `"+targetURL+"`.") - if !isNamespaceRemoval(targetURL) { + if !isNamespaceRemoval(ctx, targetURL) { printMsg(removeBucketMessage{ Bucket: targetURL, Status: "success", }) diff --git a/cmd/retention-main.go b/cmd/retention-main.go index 48fff8d5..fac85826 100644 --- a/cmd/retention-main.go +++ b/cmd/retention-main.go @@ -17,6 +17,7 @@ package cmd import ( + "context" "fmt" "strconv" "strings" @@ -116,6 +117,9 @@ func getRetainUntilDate(validity uint64, unit minio.ValidityUnit) (string, *prob // setRetention - Set Retention for all objects within a given prefix. func setRetention(urlStr string, mode minio.RetentionMode, validity uint64, unit minio.ValidityUnit, bypassGovernance, isRecursive bool) error { + ctx, cancelSetRetention := context.WithCancel(globalContext) + defer cancelSetRetention() + clnt, err := newClient(urlStr) if err != nil { fatalIf(err.Trace(), "Cannot parse the provided url.") @@ -130,7 +134,7 @@ func setRetention(urlStr string, mode minio.RetentionMode, validity uint64, unit alias, _, _ := mustExpandAlias(urlStr) var cErr error - for content := range clnt.List(isRecursive, false, false, DirNone) { + for content := range clnt.List(ctx, isRecursive, false, false, DirNone) { if content.Err != nil { errorIf(content.Err.Trace(clnt.GetURL().String()), "Unable to list folder.") cErr = exitStatus(globalErrorExitStatus) // Set the exit status. @@ -152,7 +156,7 @@ func setRetention(urlStr string, mode minio.RetentionMode, validity uint64, unit errorIf(err.Trace(clnt.GetURL().String()), "Invalid URL") continue } - err = newClnt.PutObjectRetention(mode, retainUntil, bypassGovernance) + err = newClnt.PutObjectRetention(ctx, mode, retainUntil, bypassGovernance) if err != nil { printMsg(retentionCmdMessage{ Mode: mode, diff --git a/cmd/rm-main.go b/cmd/rm-main.go index 99fa2122..ed3f275b 100644 --- a/cmd/rm-main.go +++ b/cmd/rm-main.go @@ -18,6 +18,7 @@ package cmd import ( "bufio" + "context" "fmt" "os" "path/filepath" @@ -148,20 +149,20 @@ func (r rmMessage) JSON() string { } // Validate command line arguments. -func checkRmSyntax(ctx *cli.Context, encKeyDB map[string][]prefixSSEPair) { +func checkRmSyntax(ctx context.Context, cliCtx *cli.Context, encKeyDB map[string][]prefixSSEPair) { // Set command flags from context. - isForce := ctx.Bool("force") - isRecursive := ctx.Bool("recursive") - isStdin := ctx.Bool("stdin") - isDangerous := ctx.Bool("dangerous") + isForce := cliCtx.Bool("force") + isRecursive := cliCtx.Bool("recursive") + isStdin := cliCtx.Bool("stdin") + isDangerous := cliCtx.Bool("dangerous") isNamespaceRemoval := false - for _, url := range ctx.Args() { + for _, url := range cliCtx.Args() { // clean path for aliases like s3/. // 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(url, encKeyDB) + dir := isAliasURLDir(ctx, url, encKeyDB) if !dir { _, path := url2Alias(url) isNamespaceRemoval = (path == "") @@ -176,9 +177,9 @@ func checkRmSyntax(ctx *cli.Context, encKeyDB map[string][]prefixSSEPair) { "Removal requires --recursive flag. This operation is *IRREVERSIBLE*. Please review carefully before performing this *DANGEROUS* operation.") } } - if !ctx.Args().Present() && !isStdin { + if !cliCtx.Args().Present() && !isStdin { exitCode := 1 - cli.ShowCommandHelpAndExit(ctx, "rm", exitCode) + cli.ShowCommandHelpAndExit(cliCtx, "rm", exitCode) } // For all recursive operations make sure to check for 'force' flag. @@ -197,8 +198,11 @@ func checkRmSyntax(ctx *cli.Context, encKeyDB map[string][]prefixSSEPair) { } func removeSingle(url string, isIncomplete, isFake, isForce, isBypass bool, olderThan, newerThan string, encKeyDB map[string][]prefixSSEPair) error { + ctx, cancelRemoveSingle := context.WithCancel(globalContext) + defer cancelRemoveSingle() + isRecursive := false - contents, pErr := statURL(url, isIncomplete, isRecursive, encKeyDB) + contents, pErr := statURL(ctx, url, isIncomplete, isRecursive, encKeyDB) if pErr != nil { errorIf(pErr.Trace(url), "Failed to remove `"+url+"`.") return exitStatus(globalErrorExitStatus) @@ -243,7 +247,7 @@ func removeSingle(url string, isIncomplete, isFake, isForce, isBypass bool, olde contentCh <- &ClientContent{URL: *newClientURL(targetURL)} close(contentCh) isRemoveBucket := false - errorCh := clnt.Remove(isIncomplete, isRemoveBucket, isBypass, contentCh) + errorCh := clnt.Remove(ctx, isIncomplete, isRemoveBucket, isBypass, contentCh) for pErr := range errorCh { if pErr != nil { errorIf(pErr.Trace(url), "Failed to remove `"+url+"`.") @@ -260,6 +264,9 @@ func removeSingle(url string, isIncomplete, isFake, isForce, isBypass bool, olde } func removeRecursive(url string, isIncomplete, isFake, isBypass bool, olderThan, newerThan string, encKeyDB map[string][]prefixSSEPair) error { + ctx, cancelRemoveRecursive := context.WithCancel(globalContext) + defer cancelRemoveRecursive() + targetAlias, targetURL, _ := mustExpandAlias(url) clnt, pErr := newClientFromAlias(targetAlias, targetURL) if pErr != nil { @@ -269,10 +276,10 @@ func removeRecursive(url string, isIncomplete, isFake, isBypass bool, olderThan, contentCh := make(chan *ClientContent) isRemoveBucket := false - errorCh := clnt.Remove(isIncomplete, isRemoveBucket, isBypass, contentCh) + errorCh := clnt.Remove(ctx, isIncomplete, isRemoveBucket, isBypass, contentCh) isRecursive := true - for content := range clnt.List(isRecursive, isIncomplete, false, DirNone) { + for content := range clnt.List(ctx, isRecursive, isIncomplete, false, DirNone) { if content.Err != nil { errorIf(content.Err.Trace(url), "Failed to remove `"+url+"` recursively.") switch content.Err.ToGoError().(type) { @@ -340,23 +347,26 @@ func removeRecursive(url string, isIncomplete, isFake, isBypass bool, olderThan, } // main for rm command. -func mainRm(ctx *cli.Context) error { +func mainRm(cliCtx *cli.Context) error { + ctx, cancelRm := context.WithCancel(globalContext) + defer cancelRm() + // Parse encryption keys per command. - encKeyDB, err := getEncKeys(ctx) + encKeyDB, err := getEncKeys(cliCtx) fatalIf(err, "Unable to parse encryption keys.") // check 'rm' cli arguments. - checkRmSyntax(ctx, encKeyDB) + checkRmSyntax(ctx, cliCtx, encKeyDB) // rm specific flags. - isIncomplete := ctx.Bool("incomplete") - isRecursive := ctx.Bool("recursive") - isFake := ctx.Bool("fake") - isStdin := ctx.Bool("stdin") - isBypass := ctx.Bool(bypass) - olderThan := ctx.String("older-than") - newerThan := ctx.String("newer-than") - isForce := ctx.Bool("force") + isIncomplete := cliCtx.Bool("incomplete") + isRecursive := cliCtx.Bool("recursive") + isFake := cliCtx.Bool("fake") + isStdin := cliCtx.Bool("stdin") + isBypass := cliCtx.Bool(bypass) + olderThan := cliCtx.String("older-than") + newerThan := cliCtx.String("newer-than") + isForce := cliCtx.Bool("force") // Set color. console.SetColor("Remove", color.New(color.FgGreen, color.Bold)) @@ -364,7 +374,7 @@ func mainRm(ctx *cli.Context) error { var rerr error var e error // Support multiple targets. - for _, url := range ctx.Args() { + for _, url := range cliCtx.Args() { if isRecursive { e = removeRecursive(url, isIncomplete, isFake, isBypass, olderThan, newerThan, encKeyDB) } else { diff --git a/cmd/share-download-main.go b/cmd/share-download-main.go index 7ebd79fa..81dcc8dd 100644 --- a/cmd/share-download-main.go +++ b/cmd/share-download-main.go @@ -17,6 +17,7 @@ package cmd import ( + "context" "strings" "time" @@ -66,15 +67,15 @@ EXAMPLES: } // checkShareDownloadSyntax - validate command-line args. -func checkShareDownloadSyntax(ctx *cli.Context, encKeyDB map[string][]prefixSSEPair) { - args := ctx.Args() +func checkShareDownloadSyntax(ctx context.Context, cliCtx *cli.Context, encKeyDB map[string][]prefixSSEPair) { + args := cliCtx.Args() if !args.Present() { - cli.ShowCommandHelpAndExit(ctx, "download", 1) // last argument is exit code. + cli.ShowCommandHelpAndExit(cliCtx, "download", 1) // last argument is exit code. } // Parse expiry. expiry := shareDefaultExpiry - expireArg := ctx.String("expire") + expireArg := cliCtx.String("expire") if expireArg != "" { var e error expiry, e = time.ParseDuration(expireArg) @@ -90,10 +91,10 @@ func checkShareDownloadSyntax(ctx *cli.Context, encKeyDB map[string][]prefixSSEP } // Validate if object exists only if the `--recursive` flag was NOT specified - isRecursive := ctx.Bool("recursive") + isRecursive := cliCtx.Bool("recursive") if !isRecursive { - for _, url := range ctx.Args() { - _, _, err := url2Stat(url, false, encKeyDB) + for _, url := range cliCtx.Args() { + _, _, err := url2Stat(ctx, url, false, encKeyDB) if err != nil { fatalIf(err.Trace(url), "Unable to stat `"+url+"`.") } @@ -102,7 +103,7 @@ func checkShareDownloadSyntax(ctx *cli.Context, encKeyDB map[string][]prefixSSEP } // doShareURL share files from target. -func doShareDownloadURL(targetURL string, isRecursive bool, expiry time.Duration) *probe.Error { +func doShareDownloadURL(ctx context.Context, targetURL string, isRecursive bool, expiry time.Duration) *probe.Error { targetAlias, targetURLFull, _, err := expandAlias(targetURL) if err != nil { return err.Trace(targetURL) @@ -125,7 +126,7 @@ func doShareDownloadURL(targetURL string, isRecursive bool, expiry time.Duration // Channel which will receive objects whose URLs need to be shared objectsCh := make(chan *ClientContent) - content, err := clnt.Stat(isIncomplete, false, nil) + content, err := clnt.Stat(ctx, isIncomplete, false, nil) if err != nil { return err.Trace(clnt.GetURL().String()) } @@ -146,7 +147,7 @@ func doShareDownloadURL(targetURL string, isRecursive bool, expiry time.Duration // Recursive mode: Share list of objects go func() { defer close(objectsCh) - for content := range clnt.List(isRecursive, isIncomplete, false, DirNone) { + for content := range clnt.List(ctx, isRecursive, isIncomplete, false, DirNone) { objectsCh <- content } }() @@ -168,7 +169,7 @@ func doShareDownloadURL(targetURL string, isRecursive bool, expiry time.Duration } // Generate share URL. - shareURL, err := newClnt.ShareDownload(expiry) + shareURL, err := newClnt.ShareDownload(ctx, expiry) if err != nil { // add objectURL and expiry as part of the trace arguments. return err.Trace(objectURL, "expiry="+expiry.String()) @@ -190,13 +191,16 @@ func doShareDownloadURL(targetURL string, isRecursive bool, expiry time.Duration } // main for share download. -func mainShareDownload(ctx *cli.Context) error { +func mainShareDownload(cliCtx *cli.Context) error { + ctx, cancelShareDownload := context.WithCancel(globalContext) + defer cancelShareDownload() + // Parse encryption keys per command. - encKeyDB, err := getEncKeys(ctx) + encKeyDB, err := getEncKeys(cliCtx) fatalIf(err, "Unable to parse encryption keys.") // check input arguments. - checkShareDownloadSyntax(ctx, encKeyDB) + checkShareDownloadSyntax(ctx, cliCtx, encKeyDB) // Initialize share config folder. initShareConfig() @@ -205,16 +209,16 @@ func mainShareDownload(ctx *cli.Context) error { shareSetColor() // Set command flags from context. - isRecursive := ctx.Bool("recursive") + isRecursive := cliCtx.Bool("recursive") expiry := shareDefaultExpiry - if ctx.String("expire") != "" { + if cliCtx.String("expire") != "" { var e error - expiry, e = time.ParseDuration(ctx.String("expire")) - fatalIf(probe.NewError(e), "Unable to parse expire=`"+ctx.String("expire")+"`.") + expiry, e = time.ParseDuration(cliCtx.String("expire")) + fatalIf(probe.NewError(e), "Unable to parse expire=`"+cliCtx.String("expire")+"`.") } - for _, targetURL := range ctx.Args() { - err := doShareDownloadURL(targetURL, isRecursive, expiry) + for _, targetURL := range cliCtx.Args() { + err := doShareDownloadURL(ctx, targetURL, isRecursive, expiry) if err != nil { switch err.ToGoError().(type) { case APINotImplemented: diff --git a/cmd/signals.go b/cmd/signals.go index b3471bce..15954a1a 100644 --- a/cmd/signals.go +++ b/cmd/signals.go @@ -35,8 +35,10 @@ func trapSignals(sig ...os.Signal) { <-sigCh // Once signal has been received stop signal Notify handler. + signal.Stop(sigCh) // Cancel the global context globalCancel() + } diff --git a/cmd/sql-main.go b/cmd/sql-main.go index 7d5f2c75..215a02d7 100644 --- a/cmd/sql-main.go +++ b/cmd/sql-main.go @@ -20,6 +20,7 @@ import ( "bufio" "compress/bzip2" "compress/gzip" + "context" "errors" "fmt" "io" @@ -308,7 +309,7 @@ func getCSVHeader(sourceURL string, encKeyDB map[string][]prefixSSEPair) ([]stri default: var err *probe.Error var metadata map[string]string - if r, metadata, err = getSourceStreamMetadataFromURL(sourceURL, encKeyDB); err != nil { + if r, metadata, err = getSourceStreamMetadataFromURL(globalContext, sourceURL, encKeyDB); err != nil { return nil, err.Trace(sourceURL) } ctype := metadata["Content-Type"] @@ -381,6 +382,9 @@ func isCSVOrJSON(inOpts map[string]map[string]string) bool { } func sqlSelect(targetURL, expression string, encKeyDB map[string][]prefixSSEPair, selOpts SelectObjectOpts, csvHdrs []string, writeHdr bool) *probe.Error { + ctx, cancelSelect := context.WithCancel(globalContext) + defer cancelSelect() + alias, _, _, err := expandAlias(targetURL) if err != nil { return err.Trace(targetURL) @@ -392,7 +396,7 @@ func sqlSelect(targetURL, expression string, encKeyDB map[string][]prefixSSEPair } sseKey := getSSE(targetURL, encKeyDB[alias]) - outputer, err := targetClnt.Select(expression, sseKey, selOpts) + outputer, err := targetClnt.Select(ctx, expression, sseKey, selOpts) if err != nil { return err.Trace(targetURL, expression) } @@ -430,28 +434,31 @@ func checkSQLSyntax(ctx *cli.Context) { } // mainSQL is the main entry point for sql command. -func mainSQL(ctx *cli.Context) error { +func mainSQL(cliCtx *cli.Context) error { + ctx, cancelSQL := context.WithCancel(globalContext) + defer cancelSQL() + var ( csvHdrs []string selOpts SelectObjectOpts query string ) // Parse encryption keys per command. - encKeyDB, err := getEncKeys(ctx) + encKeyDB, err := getEncKeys(cliCtx) fatalIf(err, "Unable to parse encryption keys.") // validate sql input arguments. - checkSQLSyntax(ctx) + checkSQLSyntax(cliCtx) // extract URLs. - URLs := ctx.Args() + URLs := cliCtx.Args() writeHdr := true for _, url := range URLs { - if _, targetContent, err := url2Stat(url, false, encKeyDB); err != nil { + if _, targetContent, err := url2Stat(ctx, url, false, encKeyDB); err != nil { errorIf(err.Trace(url), "Unable to run sql for "+url+".") continue } else if !targetContent.Type.IsDir() { if writeHdr { - query, csvHdrs, selOpts = getAndValidateArgs(ctx, encKeyDB, url) + query, csvHdrs, selOpts = getAndValidateArgs(cliCtx, encKeyDB, url) } errorIf(sqlSelect(url, query, encKeyDB, selOpts, csvHdrs, writeHdr).Trace(url), "Unable to run sql") writeHdr = false @@ -464,13 +471,13 @@ func mainSQL(ctx *cli.Context) error { continue } - for content := range clnt.List(ctx.Bool("recursive"), false, false, DirNone) { + for content := range clnt.List(ctx, cliCtx.Bool("recursive"), false, false, DirNone) { if content.Err != nil { errorIf(content.Err.Trace(url), "Unable to list on target `"+url+"`.") continue } if writeHdr { - query, csvHdrs, selOpts = getAndValidateArgs(ctx, encKeyDB, targetAlias+content.URL.Path) + query, csvHdrs, selOpts = getAndValidateArgs(cliCtx, encKeyDB, targetAlias+content.URL.Path) } contentType := mimedb.TypeByExtension(filepath.Ext(content.URL.Path)) for _, cTypeSuffix := range supportedContentTypes { diff --git a/cmd/stat-main.go b/cmd/stat-main.go index 04c9f409..6caaf9ba 100644 --- a/cmd/stat-main.go +++ b/cmd/stat-main.go @@ -17,6 +17,7 @@ package cmd import ( + "context" "strings" "github.com/fatih/color" @@ -73,23 +74,23 @@ EXAMPLES: } // checkStatSyntax - validate all the passed arguments -func checkStatSyntax(ctx *cli.Context, encKeyDB map[string][]prefixSSEPair) { - if !ctx.Args().Present() { - cli.ShowCommandHelpAndExit(ctx, "stat", 1) // last argument is exit code +func checkStatSyntax(ctx context.Context, cliCtx *cli.Context, encKeyDB map[string][]prefixSSEPair) { + if !cliCtx.Args().Present() { + cli.ShowCommandHelpAndExit(cliCtx, "stat", 1) // last argument is exit code } - args := ctx.Args() + args := cliCtx.Args() for _, arg := range args { if strings.TrimSpace(arg) == "" { fatalIf(errInvalidArgument().Trace(args...), "Unable to validate empty argument.") } } // extract URLs. - URLs := ctx.Args() + URLs := cliCtx.Args() isIncomplete := false for _, url := range URLs { - _, _, err := url2Stat(url, false, encKeyDB) + _, _, err := url2Stat(ctx, url, false, encKeyDB) if err != nil && !isURLPrefixExists(url, isIncomplete) { fatalIf(err.Trace(url), "Unable to stat `"+url+"`.") } @@ -97,7 +98,10 @@ func checkStatSyntax(ctx *cli.Context, encKeyDB map[string][]prefixSSEPair) { } // mainStat - is a handler for mc stat command -func mainStat(ctx *cli.Context) error { +func mainStat(cliCtx *cli.Context) error { + ctx, cancelStat := context.WithCancel(globalContext) + defer cancelStat() + // Additional command specific theme customization. console.SetColor("Name", color.New(color.Bold, color.FgCyan)) console.SetColor("Date", color.New(color.FgWhite)) @@ -106,24 +110,24 @@ func mainStat(ctx *cli.Context) error { console.SetColor("Metadata", color.New(color.FgWhite)) // Parse encryption keys per command. - encKeyDB, err := getEncKeys(ctx) + encKeyDB, err := getEncKeys(cliCtx) fatalIf(err, "Unable to parse encryption keys.") // check 'stat' cli arguments. - checkStatSyntax(ctx, encKeyDB) + checkStatSyntax(ctx, cliCtx, encKeyDB) // Set command flags from context. - isRecursive := ctx.Bool("recursive") + isRecursive := cliCtx.Bool("recursive") - args := ctx.Args() + args := cliCtx.Args() // mimic operating system tool behavior. - if !ctx.Args().Present() { + if !cliCtx.Args().Present() { args = []string{"."} } var cErr error for _, targetURL := range args { - stats, err := statURL(targetURL, false, isRecursive, encKeyDB) + stats, err := statURL(ctx, targetURL, false, isRecursive, encKeyDB) if err != nil { fatalIf(err, "Unable to stat `"+targetURL+"`.") } diff --git a/cmd/stat.go b/cmd/stat.go index 3c53df91..b08d51a9 100644 --- a/cmd/stat.go +++ b/cmd/stat.go @@ -17,6 +17,7 @@ package cmd import ( + "context" "fmt" "path/filepath" "strings" @@ -127,7 +128,7 @@ func getStandardizedURL(targetURL string) string { } // statURL - simple or recursive listing -func statURL(targetURL string, isIncomplete, isRecursive bool, encKeyDB map[string][]prefixSSEPair) ([]*ClientContent, *probe.Error) { +func statURL(ctx context.Context, targetURL string, isIncomplete, isRecursive bool, encKeyDB map[string][]prefixSSEPair) ([]*ClientContent, *probe.Error) { var stats []*ClientContent var clnt Client clnt, err := newClient(targetURL) @@ -143,7 +144,7 @@ func statURL(targetURL string, isIncomplete, isRecursive bool, encKeyDB map[stri prefixPath = prefixPath[:strings.LastIndex(prefixPath, separator)+1] } var cErr error - for content := range clnt.List(isRecursive, isIncomplete, false, DirNone) { + for content := range clnt.List(ctx, isRecursive, isIncomplete, false, DirNone) { if content.Err != nil { switch content.Err.ToGoError().(type) { // handle this specifically for filesystem related errors. @@ -176,7 +177,7 @@ func statURL(targetURL string, isIncomplete, isRecursive bool, encKeyDB map[stri return nil, errTargetNotFound(targetURL).Trace(url, standardizedURL) } - _, stat, err := url2Stat(url, true, encKeyDB) + _, stat, err := url2Stat(ctx, url, true, encKeyDB) if err != nil { stat = content } diff --git a/cmd/tag-list.go b/cmd/tag-list.go index eb4f0b06..6e5f5e7e 100644 --- a/cmd/tag-list.go +++ b/cmd/tag-list.go @@ -17,6 +17,7 @@ package cmd import ( + "context" "errors" "fmt" "sort" @@ -100,16 +101,19 @@ func (t tagListMessage) String() string { return strings.Join(strs, "\n") } -func mainListTag(ctx *cli.Context) error { - if len(ctx.Args()) != 1 { - cli.ShowCommandHelpAndExit(ctx, "list", globalErrorExitStatus) +func mainListTag(cliCtx *cli.Context) error { + ctx, cancelListTag := context.WithCancel(globalContext) + defer cancelListTag() + + if len(cliCtx.Args()) != 1 { + cli.ShowCommandHelpAndExit(cliCtx, "list", globalErrorExitStatus) } - targetURL := ctx.Args().Get(0) + targetURL := cliCtx.Args().Get(0) clnt, err := newClient(targetURL) fatalIf(err, "Unable to initialize target "+targetURL) - tags, err := clnt.GetTags() + tags, err := clnt.GetTags(ctx) fatalIf(err, "Unable to fetch tags for "+targetURL) tagMap := tags.ToMap() diff --git a/cmd/tag-remove.go b/cmd/tag-remove.go index e42419f1..58c587b2 100644 --- a/cmd/tag-remove.go +++ b/cmd/tag-remove.go @@ -17,6 +17,8 @@ package cmd import ( + "context" + "github.com/fatih/color" "github.com/minio/cli" json "github.com/minio/mc/pkg/colorjson" @@ -74,15 +76,18 @@ func checkRemoveTagSyntax(ctx *cli.Context) { } } -func mainRemoveTag(ctx *cli.Context) error { - checkRemoveTagSyntax(ctx) +func mainRemoveTag(cliCtx *cli.Context) error { + ctx, cancelList := context.WithCancel(globalContext) + defer cancelList() + + checkRemoveTagSyntax(cliCtx) console.SetColor("Remove", color.New(color.FgGreen)) - targetURL := ctx.Args().Get(0) + targetURL := cliCtx.Args().Get(0) clnt, pErr := newClient(targetURL) fatalIf(pErr, "Unable to initialize target "+targetURL) - pErr = clnt.DeleteTags() + pErr = clnt.DeleteTags(ctx) fatalIf(pErr, "Unable to remove tags for "+targetURL) printMsg(tagRemoveMessage{ diff --git a/cmd/tag-set.go b/cmd/tag-set.go index a2f443eb..6803e2f2 100644 --- a/cmd/tag-set.go +++ b/cmd/tag-set.go @@ -17,6 +17,8 @@ package cmd import ( + "context" + "github.com/fatih/color" "github.com/minio/cli" json "github.com/minio/mc/pkg/colorjson" @@ -75,17 +77,20 @@ func checkSetTagSyntax(ctx *cli.Context) { } } -func mainSetTag(ctx *cli.Context) error { - checkSetTagSyntax(ctx) +func mainSetTag(cliCtx *cli.Context) error { + ctx, cancelSetTag := context.WithCancel(globalContext) + defer cancelSetTag() + + checkSetTagSyntax(cliCtx) console.SetColor("List", color.New(color.FgGreen)) - targetURL := ctx.Args().Get(0) - tags := ctx.Args().Get(1) + targetURL := cliCtx.Args().Get(0) + tags := cliCtx.Args().Get(1) clnt, err := newClient(targetURL) - fatalIf(err.Trace(ctx.Args()...), "Unable to initialize target "+targetURL) + fatalIf(err.Trace(cliCtx.Args()...), "Unable to initialize target "+targetURL) - fatalIf(clnt.SetTags(tags).Trace(tags), "Failed to set tags for "+targetURL) + fatalIf(clnt.SetTags(ctx, tags).Trace(tags), "Failed to set tags for "+targetURL) printMsg(tagSetMessage{ Status: "success", diff --git a/cmd/tree-main.go b/cmd/tree-main.go index 621af6a3..f06df003 100644 --- a/cmd/tree-main.go +++ b/cmd/tree-main.go @@ -17,6 +17,7 @@ package cmd import ( + "context" "errors" "fmt" "path/filepath" @@ -105,11 +106,11 @@ EXAMPLES: } // checkTreeSyntax - validate all the passed arguments -func checkTreeSyntax(ctx *cli.Context) { - args := ctx.Args() +func checkTreeSyntax(ctx context.Context, cliCtx *cli.Context) { + args := cliCtx.Args() - if ctx.IsSet("depth") { - if ctx.Int("depth") < -1 || ctx.Int("depth") == 0 { + if cliCtx.IsSet("depth") { + if cliCtx.Int("depth") < -1 || cliCtx.Int("depth") == 0 { fatalIf(errInvalidArgument().Trace(args...), "please set a proper depth, for example: '--depth 1' to limit the tree output, default (-1) output displays everything") } } @@ -119,14 +120,14 @@ func checkTreeSyntax(ctx *cli.Context) { } for _, url := range args { - if _, _, err := url2Stat(url, false, nil); err != nil && !isURLPrefixExists(url, false) { + if _, _, err := url2Stat(ctx, url, false, nil); err != nil && !isURLPrefixExists(url, false) { fatalIf(err.Trace(url), "Unable to tree `"+url+"`.") } } } // doTree - list all entities inside a folder in a tree format. -func doTree(url string, level int, leaf bool, branchString string, depth int, includeFiles bool) error { +func doTree(ctx context.Context, url string, level int, leaf bool, branchString string, depth int, includeFiles bool) error { targetAlias, targetURL, _ := mustExpandAlias(url) if !strings.HasSuffix(targetURL, "/") { @@ -206,7 +207,7 @@ func doTree(url string, level int, leaf bool, branchString string, depth int, in } if depth == -1 || level <= depth { - if err := doTree(url, level+1, end, currbranchString, depth, includeFiles); err != nil { + if err := doTree(ctx, url, level+1, end, currbranchString, depth, includeFiles); err != nil { return err } } @@ -215,7 +216,7 @@ func doTree(url string, level int, leaf bool, branchString string, depth int, in return nil } - for content := range clnt.List(false, false, false, DirNone) { + for content := range clnt.List(ctx, false, false, false, DirNone) { if !includeFiles && !content.Type.IsDir() { continue @@ -245,27 +246,29 @@ func doTree(url string, level int, leaf bool, branchString string, depth int, in } // mainTree - is a handler for mc tree command -func mainTree(ctx *cli.Context) error { +func mainTree(cliCtx *cli.Context) error { + ctx, cancelList := context.WithCancel(globalContext) + defer cancelList() - // check 'tree' cli arguments. - checkTreeSyntax(ctx) + // check 'tree' cliCtx arguments. + checkTreeSyntax(ctx, cliCtx) console.SetColor("File", color.New(color.Bold)) console.SetColor("Dir", color.New(color.FgCyan, color.Bold)) - args := ctx.Args() + args := cliCtx.Args() // mimic operating system tool behavior. - if !ctx.Args().Present() { + if !cliCtx.Args().Present() { args = []string{"."} } - includeFiles := ctx.Bool("files") - depth := ctx.Int("depth") + includeFiles := cliCtx.Bool("files") + depth := cliCtx.Int("depth") var cErr error for _, targetURL := range args { if !globalJSON { - if e := doTree(targetURL, 1, false, "", depth, includeFiles); e != nil { + if e := doTree(ctx, targetURL, 1, false, "", depth, includeFiles); e != nil { cErr = e } } else { @@ -275,7 +278,7 @@ func mainTree(ctx *cli.Context) error { } clnt, err := newClientFromAlias(targetAlias, targetURL) fatalIf(err.Trace(targetURL), "Unable to initialize target `"+targetURL+"`.") - if e := doList(clnt, true, false); e != nil { + if e := doList(ctx, clnt, true, false); e != nil { cErr = e } } diff --git a/cmd/watch-main.go b/cmd/watch-main.go index f9f54666..5f10037c 100644 --- a/cmd/watch-main.go +++ b/cmd/watch-main.go @@ -17,6 +17,7 @@ package cmd import ( + "context" "fmt" "strings" "sync" @@ -129,21 +130,21 @@ func (u watchMessage) String() string { return msg } -func mainWatch(ctx *cli.Context) error { +func mainWatch(cliCtx *cli.Context) error { console.SetColor("Time", color.New(color.FgGreen)) console.SetColor("Size", color.New(color.FgYellow)) console.SetColor("EventType", color.New(color.FgCyan, color.Bold)) console.SetColor("ObjectName", color.New(color.Bold)) - checkWatchSyntax(ctx) + checkWatchSyntax(cliCtx) - args := ctx.Args() + args := cliCtx.Args() path := args[0] - prefix := ctx.String("prefix") - suffix := ctx.String("suffix") - events := strings.Split(ctx.String("events"), ",") - recursive := ctx.Bool("recursive") + prefix := cliCtx.String("prefix") + suffix := cliCtx.String("suffix") + events := strings.Split(cliCtx.String("events"), ",") + recursive := cliCtx.Bool("recursive") s3Client, pErr := newClient(path) if pErr != nil { @@ -157,8 +158,11 @@ func mainWatch(ctx *cli.Context) error { Suffix: suffix, } + ctx, cancelWatch := context.WithCancel(globalContext) + defer cancelWatch() + // Start watching on events - wo, err := s3Client.Watch(options) + wo, err := s3Client.Watch(ctx, options) fatalIf(err, "Cannot watch on the specified bucket.") // Initialize.. waitgroup to track the go-routine. diff --git a/cmd/watch.go b/cmd/watch.go index 921cab3f..bff3cb0c 100644 --- a/cmd/watch.go +++ b/cmd/watch.go @@ -17,6 +17,7 @@ package cmd import ( + "context" "sync" "time" @@ -140,8 +141,8 @@ func (w *Watcher) Wait() { } // Join the watcher with client -func (w *Watcher) Join(client Client, recursive bool) *probe.Error { - wo, err := client.Watch(WatchOptions{ +func (w *Watcher) Join(ctx context.Context, client Client, recursive bool) *probe.Error { + wo, err := client.Watch(ctx, WatchOptions{ Recursive: recursive, Events: []string{"put", "delete"}, }) diff --git a/go.mod b/go.mod index 5bb443fc..0b3f6689 100644 --- a/go.mod +++ b/go.mod @@ -17,7 +17,7 @@ require ( github.com/mattn/go-runewidth v0.0.5 // indirect github.com/minio/cli v1.22.0 github.com/minio/minio v0.0.0-20200527010300-cccf2de129da - github.com/minio/minio-go/v6 v6.0.56-0.20200522164946-44a5f2e3b76b + github.com/minio/minio-go/v6 v6.0.58-0.20200612001654-a57fec8037ec github.com/minio/sha256-simd v0.1.1 github.com/mitchellh/go-homedir v1.1.0 github.com/pkg/profile v1.3.0 diff --git a/go.sum b/go.sum index 876c011b..fa9cca79 100644 --- a/go.sum +++ b/go.sum @@ -217,6 +217,7 @@ github.com/klauspost/compress v1.10.3 h1:OP96hzwJVBIHYU52pVTI6CczrxPvrGfgqF9N5eT github.com/klauspost/compress v1.10.3/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdYsUV+/s2qKfXs= github.com/klauspost/cpuid v1.2.2 h1:1xAgYebNnsb9LKCdLOvFWtAxGU/33mjJtyOVbmUa0Us= github.com/klauspost/cpuid v1.2.2/go.mod h1:Pj4uuM528wm8OyEC2QMXAi2YiTZ96dNQPGgoMS4s3ek= +github.com/klauspost/cpuid v1.2.3/go.mod h1:Pj4uuM528wm8OyEC2QMXAi2YiTZ96dNQPGgoMS4s3ek= github.com/klauspost/cpuid v1.2.4 h1:EBfaK0SWSwk+fgk6efYFWdzl8MwRWoOO1gkmiaTXPW4= github.com/klauspost/cpuid v1.2.4/go.mod h1:Pj4uuM528wm8OyEC2QMXAi2YiTZ96dNQPGgoMS4s3ek= github.com/klauspost/pgzip v1.2.1 h1:oIPZROsWuPHpOdMVWLuJZXwgjhrW8r1yEX8UqMyeNHM= @@ -273,6 +274,8 @@ github.com/minio/highwayhash v1.0.0 h1:iMSDhgUILCr0TNm8LWlSjF8N0ZIj2qbO8WHp6Q/J2 github.com/minio/highwayhash v1.0.0/go.mod h1:xQboMTeM9nY9v/LlAOxFctujiv5+Aq2hR5dxBpaMbdc= github.com/minio/lsync v1.0.1 h1:AVvILxA976xc27hstd1oR+X9PQG0sPSom1MNb1ImfUs= github.com/minio/lsync v1.0.1/go.mod h1:tCFzfo0dlvdGl70IT4IAK/5Wtgb0/BrTmo/jE8pArKA= +github.com/minio/md5-simd v1.1.0 h1:QPfiOqlZH+Cj9teu0t9b1nTBfPbyTl16Of5MeuShdK4= +github.com/minio/md5-simd v1.1.0/go.mod h1:XpBqgZULrMYD3R+M28PcmP0CkI7PEMzB3U77ZrKZ0Gw= github.com/minio/minio v0.0.0-20200421050159-282c9f790a03 h1:qEWJAXNbLp1Uovs9gzPQ8gWGFY8X+58WcttySAMgny0= github.com/minio/minio v0.0.0-20200421050159-282c9f790a03/go.mod h1:zBua5AiljGs1Irdl2XEyiJjvZVCVDIG8gjozzRBcVlw= github.com/minio/minio v0.0.0-20200506184406-a2ccba69e563 h1:1HoqFH4py7JBKeLkKtPUrL8CsrucHsUcvrvyrisPgtA= @@ -286,6 +289,8 @@ github.com/minio/minio-go/v6 v6.0.56-0.20200502013257-a81c8c13cc3f h1:ifHrI8+exq github.com/minio/minio-go/v6 v6.0.56-0.20200502013257-a81c8c13cc3f/go.mod h1:KQMM+/44DSlSGSQWSfRrAZ12FVMmpWNuX37i2AX0jfI= github.com/minio/minio-go/v6 v6.0.56-0.20200522164946-44a5f2e3b76b h1:hY8tAl7MwUuUB9ZqVDXEnrIqCuEy3dfU1RH0cZ7gu+o= github.com/minio/minio-go/v6 v6.0.56-0.20200522164946-44a5f2e3b76b/go.mod h1:KQMM+/44DSlSGSQWSfRrAZ12FVMmpWNuX37i2AX0jfI= +github.com/minio/minio-go/v6 v6.0.58-0.20200612001654-a57fec8037ec h1:my1ShPzUyV5BSteRVdm/YoEhd4ycLImlN4xDX17pd8A= +github.com/minio/minio-go/v6 v6.0.58-0.20200612001654-a57fec8037ec/go.mod h1:5+R/nM9Pwrh0vqF+HbYYDQ84wdUFPyXHkrdT4AIkifM= github.com/minio/parquet-go v0.0.0-20200414234858-838cfa8aae61 h1:pUSI/WKPdd77gcuoJkSzhJ4wdS8OMDOsOu99MtpXEQA= github.com/minio/parquet-go v0.0.0-20200414234858-838cfa8aae61/go.mod h1:4trzEJ7N1nBTd5Tt7OCZT5SEin+WiAXpdJ/WgPkESA8= github.com/minio/sha256-simd v0.1.1 h1:5QHSlgo3nt5yKOJrC7W8w7X+NFl8cMPZm96iu8kKUJU=