api-notification.go 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. /*
  2. * MinIO Go Library for Amazon S3 Compatible Cloud Storage
  3. * Copyright 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 s3cli
  18. import (
  19. "bufio"
  20. "context"
  21. "encoding/json"
  22. "net/http"
  23. "net/url"
  24. "time"
  25. "github.com/minio/minio-go/v6/pkg/s3utils"
  26. )
  27. // GetBucketNotification - get bucket notification at a given path.
  28. func (c Client) GetBucketNotification(bucketName string) (bucketNotification BucketNotification, err error) {
  29. // Input validation.
  30. if err := s3utils.CheckValidBucketName(bucketName); err != nil {
  31. return BucketNotification{}, err
  32. }
  33. notification, err := c.getBucketNotification(bucketName)
  34. if err != nil {
  35. return BucketNotification{}, err
  36. }
  37. return notification, nil
  38. }
  39. // Request server for notification rules.
  40. func (c Client) getBucketNotification(bucketName string) (BucketNotification, error) {
  41. urlValues := make(url.Values)
  42. urlValues.Set("notification", "")
  43. // Execute GET on bucket to list objects.
  44. resp, err := c.executeMethod(context.Background(), "GET", requestMetadata{
  45. bucketName: bucketName,
  46. queryValues: urlValues,
  47. contentSHA256Hex: emptySHA256Hex,
  48. })
  49. defer closeResponse(resp)
  50. if err != nil {
  51. return BucketNotification{}, err
  52. }
  53. return processBucketNotificationResponse(bucketName, resp)
  54. }
  55. // processes the GetNotification http response from the server.
  56. func processBucketNotificationResponse(bucketName string, resp *http.Response) (BucketNotification, error) {
  57. if resp.StatusCode != http.StatusOK {
  58. errResponse := httpRespToErrorResponse(resp, bucketName, "")
  59. return BucketNotification{}, errResponse
  60. }
  61. var bucketNotification BucketNotification
  62. err := xmlDecoder(resp.Body, &bucketNotification)
  63. if err != nil {
  64. return BucketNotification{}, err
  65. }
  66. return bucketNotification, nil
  67. }
  68. // Indentity represents the user id, this is a compliance field.
  69. type identity struct {
  70. PrincipalID string `json:"principalId"`
  71. }
  72. // Notification event bucket metadata.
  73. type bucketMeta struct {
  74. Name string `json:"name"`
  75. OwnerIdentity identity `json:"ownerIdentity"`
  76. ARN string `json:"arn"`
  77. }
  78. // Notification event object metadata.
  79. type objectMeta struct {
  80. Key string `json:"key"`
  81. Size int64 `json:"size,omitempty"`
  82. ETag string `json:"eTag,omitempty"`
  83. VersionID string `json:"versionId,omitempty"`
  84. Sequencer string `json:"sequencer"`
  85. }
  86. // Notification event server specific metadata.
  87. type eventMeta struct {
  88. SchemaVersion string `json:"s3SchemaVersion"`
  89. ConfigurationID string `json:"configurationId"`
  90. Bucket bucketMeta `json:"bucket"`
  91. Object objectMeta `json:"object"`
  92. }
  93. // sourceInfo represents information on the client that
  94. // triggered the event notification.
  95. type sourceInfo struct {
  96. Host string `json:"host"`
  97. Port string `json:"port"`
  98. UserAgent string `json:"userAgent"`
  99. }
  100. // NotificationEvent represents an Amazon an S3 bucket notification event.
  101. type NotificationEvent struct {
  102. EventVersion string `json:"eventVersion"`
  103. EventSource string `json:"eventSource"`
  104. AwsRegion string `json:"awsRegion"`
  105. EventTime string `json:"eventTime"`
  106. EventName string `json:"eventName"`
  107. UserIdentity identity `json:"userIdentity"`
  108. RequestParameters map[string]string `json:"requestParameters"`
  109. ResponseElements map[string]string `json:"responseElements"`
  110. S3 eventMeta `json:"s3"`
  111. Source sourceInfo `json:"source"`
  112. }
  113. // NotificationInfo - represents the collection of notification events, additionally
  114. // also reports errors if any while listening on bucket notifications.
  115. type NotificationInfo struct {
  116. Records []NotificationEvent
  117. Err error
  118. }
  119. // ListenBucketNotification - listen on bucket notifications.
  120. func (c Client) ListenBucketNotification(bucketName, prefix, suffix string, events []string, doneCh <-chan struct{}) <-chan NotificationInfo {
  121. notificationInfoCh := make(chan NotificationInfo, 1)
  122. // Only success, start a routine to start reading line by line.
  123. go func(notificationInfoCh chan<- NotificationInfo) {
  124. defer close(notificationInfoCh)
  125. // Validate the bucket name.
  126. if err := s3utils.CheckValidBucketName(bucketName); err != nil {
  127. notificationInfoCh <- NotificationInfo{
  128. Err: err,
  129. }
  130. return
  131. }
  132. // Check ARN partition to verify if listening bucket is supported
  133. if s3utils.IsAmazonEndpoint(*c.endpointURL) || s3utils.IsGoogleEndpoint(*c.endpointURL) {
  134. notificationInfoCh <- NotificationInfo{
  135. Err: ErrAPINotSupported("Listening for bucket notification is specific only to `minio` server endpoints"),
  136. }
  137. return
  138. }
  139. // Continuously run and listen on bucket notification.
  140. // Create a done channel to control 'ListObjects' go routine.
  141. retryDoneCh := make(chan struct{}, 1)
  142. // Indicate to our routine to exit cleanly upon return.
  143. defer close(retryDoneCh)
  144. // Prepare urlValues to pass into the request on every loop
  145. urlValues := make(url.Values)
  146. urlValues.Set("prefix", prefix)
  147. urlValues.Set("suffix", suffix)
  148. urlValues["events"] = events
  149. // Wait on the jitter retry loop.
  150. for range c.newRetryTimerContinous(time.Second, time.Second*30, MaxJitter, retryDoneCh) {
  151. // Execute GET on bucket to list objects.
  152. resp, err := c.executeMethod(context.Background(), "GET", requestMetadata{
  153. bucketName: bucketName,
  154. queryValues: urlValues,
  155. contentSHA256Hex: emptySHA256Hex,
  156. })
  157. if err != nil {
  158. notificationInfoCh <- NotificationInfo{
  159. Err: err,
  160. }
  161. return
  162. }
  163. // Validate http response, upon error return quickly.
  164. if resp.StatusCode != http.StatusOK {
  165. errResponse := httpRespToErrorResponse(resp, bucketName, "")
  166. notificationInfoCh <- NotificationInfo{
  167. Err: errResponse,
  168. }
  169. return
  170. }
  171. // Initialize a new bufio scanner, to read line by line.
  172. bio := bufio.NewScanner(resp.Body)
  173. // Unmarshal each line, returns marshalled values.
  174. for bio.Scan() {
  175. var notificationInfo NotificationInfo
  176. if err = json.Unmarshal(bio.Bytes(), &notificationInfo); err != nil {
  177. closeResponse(resp)
  178. continue
  179. }
  180. // Send notificationInfo
  181. select {
  182. case notificationInfoCh <- notificationInfo:
  183. case <-doneCh:
  184. closeResponse(resp)
  185. return
  186. }
  187. }
  188. // Close current connection before looping further.
  189. closeResponse(resp)
  190. }
  191. }(notificationInfoCh)
  192. // Returns the notification info channel, for caller to start reading from.
  193. return notificationInfoCh
  194. }