bucket-cache.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  1. /*
  2. * Minio Go Library for Amazon S3 Compatible Cloud Storage
  3. * Copyright 2015-2017 Minio, Inc.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. package minio
  18. import (
  19. "net/http"
  20. "net/url"
  21. "path"
  22. "sync"
  23. "github.com/minio/minio-go/pkg/credentials"
  24. "github.com/minio/minio-go/pkg/s3signer"
  25. "github.com/minio/minio-go/pkg/s3utils"
  26. )
  27. // bucketLocationCache - Provides simple mechanism to hold bucket
  28. // locations in memory.
  29. type bucketLocationCache struct {
  30. // mutex is used for handling the concurrent
  31. // read/write requests for cache.
  32. sync.RWMutex
  33. // items holds the cached bucket locations.
  34. items map[string]string
  35. }
  36. // newBucketLocationCache - Provides a new bucket location cache to be
  37. // used internally with the client object.
  38. func newBucketLocationCache() *bucketLocationCache {
  39. return &bucketLocationCache{
  40. items: make(map[string]string),
  41. }
  42. }
  43. // Get - Returns a value of a given key if it exists.
  44. func (r *bucketLocationCache) Get(bucketName string) (location string, ok bool) {
  45. r.RLock()
  46. defer r.RUnlock()
  47. location, ok = r.items[bucketName]
  48. return
  49. }
  50. // Set - Will persist a value into cache.
  51. func (r *bucketLocationCache) Set(bucketName string, location string) {
  52. r.Lock()
  53. defer r.Unlock()
  54. r.items[bucketName] = location
  55. }
  56. // Delete - Deletes a bucket name from cache.
  57. func (r *bucketLocationCache) Delete(bucketName string) {
  58. r.Lock()
  59. defer r.Unlock()
  60. delete(r.items, bucketName)
  61. }
  62. // GetBucketLocation - get location for the bucket name from location cache, if not
  63. // fetch freshly by making a new request.
  64. func (c Client) GetBucketLocation(bucketName string) (string, error) {
  65. if err := s3utils.CheckValidBucketName(bucketName); err != nil {
  66. return "", err
  67. }
  68. return c.getBucketLocation(bucketName)
  69. }
  70. // getBucketLocation - Get location for the bucketName from location map cache, if not
  71. // fetch freshly by making a new request.
  72. func (c Client) getBucketLocation(bucketName string) (string, error) {
  73. if err := s3utils.CheckValidBucketName(bucketName); err != nil {
  74. return "", err
  75. }
  76. // Region set then no need to fetch bucket location.
  77. if c.region != "" {
  78. return c.region, nil
  79. }
  80. if location, ok := c.bucketLocCache.Get(bucketName); ok {
  81. return location, nil
  82. }
  83. // Initialize a new request.
  84. req, err := c.getBucketLocationRequest(bucketName)
  85. if err != nil {
  86. return "", err
  87. }
  88. // Initiate the request.
  89. resp, err := c.do(req)
  90. defer closeResponse(resp)
  91. if err != nil {
  92. return "", err
  93. }
  94. location, err := processBucketLocationResponse(resp, bucketName)
  95. if err != nil {
  96. return "", err
  97. }
  98. c.bucketLocCache.Set(bucketName, location)
  99. return location, nil
  100. }
  101. // processes the getBucketLocation http response from the server.
  102. func processBucketLocationResponse(resp *http.Response, bucketName string) (bucketLocation string, err error) {
  103. if resp != nil {
  104. if resp.StatusCode != http.StatusOK {
  105. err = httpRespToErrorResponse(resp, bucketName, "")
  106. errResp := ToErrorResponse(err)
  107. // For access denied error, it could be an anonymous
  108. // request. Move forward and let the top level callers
  109. // succeed if possible based on their policy.
  110. if errResp.Code == "AccessDenied" {
  111. return "us-east-1", nil
  112. }
  113. return "", err
  114. }
  115. }
  116. // Extract location.
  117. var locationConstraint string
  118. err = xmlDecoder(resp.Body, &locationConstraint)
  119. if err != nil {
  120. return "", err
  121. }
  122. location := locationConstraint
  123. // Location is empty will be 'us-east-1'.
  124. if location == "" {
  125. location = "us-east-1"
  126. }
  127. // Location can be 'EU' convert it to meaningful 'eu-west-1'.
  128. if location == "EU" {
  129. location = "eu-west-1"
  130. }
  131. // Save the location into cache.
  132. // Return.
  133. return location, nil
  134. }
  135. // getBucketLocationRequest - Wrapper creates a new getBucketLocation request.
  136. func (c Client) getBucketLocationRequest(bucketName string) (*http.Request, error) {
  137. // Set location query.
  138. urlValues := make(url.Values)
  139. urlValues.Set("location", "")
  140. // Set get bucket location always as path style.
  141. targetURL := c.endpointURL
  142. targetURL.Path = path.Join(bucketName, "") + "/"
  143. targetURL.RawQuery = urlValues.Encode()
  144. // Get a new HTTP request for the method.
  145. req, err := http.NewRequest("GET", targetURL.String(), nil)
  146. if err != nil {
  147. return nil, err
  148. }
  149. // Set UserAgent for the request.
  150. c.setUserAgent(req)
  151. // Get credentials from the configured credentials provider.
  152. value, err := c.credsProvider.Get()
  153. if err != nil {
  154. return nil, err
  155. }
  156. var (
  157. signerType = value.SignerType
  158. accessKeyID = value.AccessKeyID
  159. secretAccessKey = value.SecretAccessKey
  160. sessionToken = value.SessionToken
  161. )
  162. // Custom signer set then override the behavior.
  163. if c.overrideSignerType != credentials.SignatureDefault {
  164. signerType = c.overrideSignerType
  165. }
  166. // If signerType returned by credentials helper is anonymous,
  167. // then do not sign regardless of signerType override.
  168. if value.SignerType == credentials.SignatureAnonymous {
  169. signerType = credentials.SignatureAnonymous
  170. }
  171. if signerType.IsAnonymous() {
  172. return req, nil
  173. }
  174. if signerType.IsV2() {
  175. // Get Bucket Location calls should be always path style
  176. isVirtualHost := false
  177. req = s3signer.SignV2(*req, accessKeyID, secretAccessKey, isVirtualHost)
  178. return req, nil
  179. }
  180. // Set sha256 sum for signature calculation only with signature version '4'.
  181. contentSha256 := emptySHA256Hex
  182. if c.secure {
  183. contentSha256 = unsignedPayload
  184. }
  185. req.Header.Set("X-Amz-Content-Sha256", contentSha256)
  186. req = s3signer.SignV4(*req, accessKeyID, secretAccessKey, sessionToken, "us-east-1")
  187. return req, nil
  188. }