api-bucket-notification.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. /*
  2. * MinIO Go Library for Amazon S3 Compatible Cloud Storage
  3. * Copyright 2017-2020 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. "bufio"
  20. "bytes"
  21. "context"
  22. "encoding/xml"
  23. "net/http"
  24. "net/url"
  25. "time"
  26. jsoniter "github.com/json-iterator/go"
  27. "github.com/minio/minio-go/v7/pkg/notification"
  28. "github.com/minio/minio-go/v7/pkg/s3utils"
  29. )
  30. // SetBucketNotification saves a new bucket notification with a context to control cancellations and timeouts.
  31. func (c Client) SetBucketNotification(ctx context.Context, bucketName string, config notification.Configuration) error {
  32. // Input validation.
  33. if err := s3utils.CheckValidBucketName(bucketName); err != nil {
  34. return err
  35. }
  36. // Get resources properly escaped and lined up before
  37. // using them in http request.
  38. urlValues := make(url.Values)
  39. urlValues.Set("notification", "")
  40. notifBytes, err := xml.Marshal(&config)
  41. if err != nil {
  42. return err
  43. }
  44. notifBuffer := bytes.NewReader(notifBytes)
  45. reqMetadata := requestMetadata{
  46. bucketName: bucketName,
  47. queryValues: urlValues,
  48. contentBody: notifBuffer,
  49. contentLength: int64(len(notifBytes)),
  50. contentMD5Base64: sumMD5Base64(notifBytes),
  51. contentSHA256Hex: sum256Hex(notifBytes),
  52. }
  53. // Execute PUT to upload a new bucket notification.
  54. resp, err := c.executeMethod(ctx, http.MethodPut, reqMetadata)
  55. defer closeResponse(resp)
  56. if err != nil {
  57. return err
  58. }
  59. if resp != nil {
  60. if resp.StatusCode != http.StatusOK {
  61. return httpRespToErrorResponse(resp, bucketName, "")
  62. }
  63. }
  64. return nil
  65. }
  66. // RemoveAllBucketNotification - Remove bucket notification clears all previously specified config
  67. func (c Client) RemoveAllBucketNotification(ctx context.Context, bucketName string) error {
  68. return c.SetBucketNotification(ctx, bucketName, notification.Configuration{})
  69. }
  70. // GetBucketNotification returns current bucket notification configuration
  71. func (c Client) GetBucketNotification(ctx context.Context, bucketName string) (bucketNotification notification.Configuration, err error) {
  72. // Input validation.
  73. if err := s3utils.CheckValidBucketName(bucketName); err != nil {
  74. return notification.Configuration{}, err
  75. }
  76. return c.getBucketNotification(ctx, bucketName)
  77. }
  78. // Request server for notification rules.
  79. func (c Client) getBucketNotification(ctx context.Context, bucketName string) (notification.Configuration, error) {
  80. urlValues := make(url.Values)
  81. urlValues.Set("notification", "")
  82. // Execute GET on bucket to list objects.
  83. resp, err := c.executeMethod(ctx, http.MethodGet, requestMetadata{
  84. bucketName: bucketName,
  85. queryValues: urlValues,
  86. contentSHA256Hex: emptySHA256Hex,
  87. })
  88. defer closeResponse(resp)
  89. if err != nil {
  90. return notification.Configuration{}, err
  91. }
  92. return processBucketNotificationResponse(bucketName, resp)
  93. }
  94. // processes the GetNotification http response from the server.
  95. func processBucketNotificationResponse(bucketName string, resp *http.Response) (notification.Configuration, error) {
  96. if resp.StatusCode != http.StatusOK {
  97. errResponse := httpRespToErrorResponse(resp, bucketName, "")
  98. return notification.Configuration{}, errResponse
  99. }
  100. var bucketNotification notification.Configuration
  101. err := xmlDecoder(resp.Body, &bucketNotification)
  102. if err != nil {
  103. return notification.Configuration{}, err
  104. }
  105. return bucketNotification, nil
  106. }
  107. // ListenNotification listen for all events, this is a MinIO specific API
  108. func (c Client) ListenNotification(ctx context.Context, prefix, suffix string, events []string) <-chan notification.Info {
  109. return c.ListenBucketNotification(ctx, "", prefix, suffix, events)
  110. }
  111. // ListenBucketNotification listen for bucket events, this is a MinIO specific API
  112. func (c Client) ListenBucketNotification(ctx context.Context, bucketName, prefix, suffix string, events []string) <-chan notification.Info {
  113. notificationInfoCh := make(chan notification.Info, 1)
  114. const notificationCapacity = 4 * 1024 * 1024
  115. notificationEventBuffer := make([]byte, notificationCapacity)
  116. // Only success, start a routine to start reading line by line.
  117. go func(notificationInfoCh chan<- notification.Info) {
  118. defer close(notificationInfoCh)
  119. // Validate the bucket name.
  120. if bucketName != "" {
  121. if err := s3utils.CheckValidBucketName(bucketName); err != nil {
  122. select {
  123. case notificationInfoCh <- notification.Info{
  124. Err: err,
  125. }:
  126. case <-ctx.Done():
  127. }
  128. return
  129. }
  130. }
  131. // Check ARN partition to verify if listening bucket is supported
  132. if s3utils.IsAmazonEndpoint(*c.endpointURL) || s3utils.IsGoogleEndpoint(*c.endpointURL) {
  133. select {
  134. case notificationInfoCh <- notification.Info{
  135. Err: errAPINotSupported("Listening for bucket notification is specific only to `minio` server endpoints"),
  136. }:
  137. case <-ctx.Done():
  138. }
  139. return
  140. }
  141. // Continuously run and listen on bucket notification.
  142. // Create a done channel to control 'ListObjects' go routine.
  143. retryDoneCh := make(chan struct{}, 1)
  144. // Indicate to our routine to exit cleanly upon return.
  145. defer close(retryDoneCh)
  146. // Prepare urlValues to pass into the request on every loop
  147. urlValues := make(url.Values)
  148. urlValues.Set("prefix", prefix)
  149. urlValues.Set("suffix", suffix)
  150. urlValues["events"] = events
  151. // Wait on the jitter retry loop.
  152. for range c.newRetryTimerContinous(time.Second, time.Second*30, MaxJitter, retryDoneCh) {
  153. // Execute GET on bucket to list objects.
  154. resp, err := c.executeMethod(ctx, http.MethodGet, requestMetadata{
  155. bucketName: bucketName,
  156. queryValues: urlValues,
  157. contentSHA256Hex: emptySHA256Hex,
  158. })
  159. if err != nil {
  160. select {
  161. case notificationInfoCh <- notification.Info{
  162. Err: err,
  163. }:
  164. case <-ctx.Done():
  165. }
  166. return
  167. }
  168. // Validate http response, upon error return quickly.
  169. if resp.StatusCode != http.StatusOK {
  170. errResponse := httpRespToErrorResponse(resp, bucketName, "")
  171. select {
  172. case notificationInfoCh <- notification.Info{
  173. Err: errResponse,
  174. }:
  175. case <-ctx.Done():
  176. }
  177. return
  178. }
  179. // Initialize a new bufio scanner, to read line by line.
  180. bio := bufio.NewScanner(resp.Body)
  181. // Use a higher buffer to support unexpected
  182. // caching done by proxies
  183. bio.Buffer(notificationEventBuffer, notificationCapacity)
  184. var json = jsoniter.ConfigCompatibleWithStandardLibrary
  185. // Unmarshal each line, returns marshaled values.
  186. for bio.Scan() {
  187. var notificationInfo notification.Info
  188. if err = json.Unmarshal(bio.Bytes(), &notificationInfo); err != nil {
  189. // Unexpected error during json unmarshal, send
  190. // the error to caller for actionable as needed.
  191. select {
  192. case notificationInfoCh <- notification.Info{
  193. Err: err,
  194. }:
  195. case <-ctx.Done():
  196. return
  197. }
  198. closeResponse(resp)
  199. continue
  200. }
  201. // Send notificationInfo
  202. select {
  203. case notificationInfoCh <- notificationInfo:
  204. case <-ctx.Done():
  205. closeResponse(resp)
  206. return
  207. }
  208. }
  209. if err = bio.Err(); err != nil {
  210. select {
  211. case notificationInfoCh <- notification.Info{
  212. Err: err,
  213. }:
  214. case <-ctx.Done():
  215. return
  216. }
  217. }
  218. // Close current connection before looping further.
  219. closeResponse(resp)
  220. }
  221. }(notificationInfoCh)
  222. // Returns the notification info channel, for caller to start reading from.
  223. return notificationInfoCh
  224. }