Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 

225 linhas
6.5 KiB

  1. // Copyright 2014 Google LLC
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package storage
  15. import (
  16. "encoding/base64"
  17. "errors"
  18. "fmt"
  19. "io"
  20. "sync"
  21. "unicode/utf8"
  22. "golang.org/x/net/context"
  23. "google.golang.org/api/googleapi"
  24. raw "google.golang.org/api/storage/v1"
  25. )
  26. // A Writer writes a Cloud Storage object.
  27. type Writer struct {
  28. // ObjectAttrs are optional attributes to set on the object. Any attributes
  29. // must be initialized before the first Write call. Nil or zero-valued
  30. // attributes are ignored.
  31. ObjectAttrs
  32. // SendCRC specifies whether to transmit a CRC32C field. It should be set
  33. // to true in addition to setting the Writer's CRC32C field, because zero
  34. // is a valid CRC and normally a zero would not be transmitted.
  35. // If a CRC32C is sent, and the data written does not match the checksum,
  36. // the write will be rejected.
  37. SendCRC32C bool
  38. // ChunkSize controls the maximum number of bytes of the object that the
  39. // Writer will attempt to send to the server in a single request. Objects
  40. // smaller than the size will be sent in a single request, while larger
  41. // objects will be split over multiple requests. The size will be rounded up
  42. // to the nearest multiple of 256K. If zero, chunking will be disabled and
  43. // the object will be uploaded in a single request.
  44. //
  45. // ChunkSize will default to a reasonable value. If you perform many concurrent
  46. // writes of small objects, you may wish set ChunkSize to a value that matches
  47. // your objects' sizes to avoid consuming large amounts of memory.
  48. //
  49. // ChunkSize must be set before the first Write call.
  50. ChunkSize int
  51. // ProgressFunc can be used to monitor the progress of a large write.
  52. // operation. If ProgressFunc is not nil and writing requires multiple
  53. // calls to the underlying service (see
  54. // https://cloud.google.com/storage/docs/json_api/v1/how-tos/resumable-upload),
  55. // then ProgressFunc will be invoked after each call with the number of bytes of
  56. // content copied so far.
  57. //
  58. // ProgressFunc should return quickly without blocking.
  59. ProgressFunc func(int64)
  60. ctx context.Context
  61. o *ObjectHandle
  62. opened bool
  63. pw *io.PipeWriter
  64. donec chan struct{} // closed after err and obj are set.
  65. obj *ObjectAttrs
  66. mu sync.Mutex
  67. err error
  68. }
  69. func (w *Writer) open() error {
  70. attrs := w.ObjectAttrs
  71. // Check the developer didn't change the object Name (this is unfortunate, but
  72. // we don't want to store an object under the wrong name).
  73. if attrs.Name != w.o.object {
  74. return fmt.Errorf("storage: Writer.Name %q does not match object name %q", attrs.Name, w.o.object)
  75. }
  76. if !utf8.ValidString(attrs.Name) {
  77. return fmt.Errorf("storage: object name %q is not valid UTF-8", attrs.Name)
  78. }
  79. if attrs.KMSKeyName != "" && w.o.encryptionKey != nil {
  80. return errors.New("storage: cannot use KMSKeyName with a customer-supplied encryption key")
  81. }
  82. pr, pw := io.Pipe()
  83. w.pw = pw
  84. w.opened = true
  85. if w.ChunkSize < 0 {
  86. return errors.New("storage: Writer.ChunkSize must be non-negative")
  87. }
  88. mediaOpts := []googleapi.MediaOption{
  89. googleapi.ChunkSize(w.ChunkSize),
  90. }
  91. if c := attrs.ContentType; c != "" {
  92. mediaOpts = append(mediaOpts, googleapi.ContentType(c))
  93. }
  94. go func() {
  95. defer close(w.donec)
  96. rawObj := attrs.toRawObject(w.o.bucket)
  97. if w.SendCRC32C {
  98. rawObj.Crc32c = encodeUint32(attrs.CRC32C)
  99. }
  100. if w.MD5 != nil {
  101. rawObj.Md5Hash = base64.StdEncoding.EncodeToString(w.MD5)
  102. }
  103. call := w.o.c.raw.Objects.Insert(w.o.bucket, rawObj).
  104. Media(pr, mediaOpts...).
  105. Projection("full").
  106. Context(w.ctx)
  107. if w.ProgressFunc != nil {
  108. call.ProgressUpdater(func(n, _ int64) { w.ProgressFunc(n) })
  109. }
  110. if attrs.KMSKeyName != "" {
  111. call.KmsKeyName(attrs.KMSKeyName)
  112. }
  113. if err := setEncryptionHeaders(call.Header(), w.o.encryptionKey, false); err != nil {
  114. w.mu.Lock()
  115. w.err = err
  116. w.mu.Unlock()
  117. pr.CloseWithError(err)
  118. return
  119. }
  120. var resp *raw.Object
  121. err := applyConds("NewWriter", w.o.gen, w.o.conds, call)
  122. if err == nil {
  123. if w.o.userProject != "" {
  124. call.UserProject(w.o.userProject)
  125. }
  126. setClientHeader(call.Header())
  127. // If the chunk size is zero, then no chunking is done on the Reader,
  128. // which means we cannot retry: the first call will read the data, and if
  129. // it fails, there is no way to re-read.
  130. if w.ChunkSize == 0 {
  131. resp, err = call.Do()
  132. } else {
  133. // We will only retry here if the initial POST, which obtains a URI for
  134. // the resumable upload, fails with a retryable error. The upload itself
  135. // has its own retry logic.
  136. err = runWithRetry(w.ctx, func() error {
  137. var err2 error
  138. resp, err2 = call.Do()
  139. return err2
  140. })
  141. }
  142. }
  143. if err != nil {
  144. w.mu.Lock()
  145. w.err = err
  146. w.mu.Unlock()
  147. pr.CloseWithError(err)
  148. return
  149. }
  150. w.obj = newObject(resp)
  151. }()
  152. return nil
  153. }
  154. // Write appends to w. It implements the io.Writer interface.
  155. //
  156. // Since writes happen asynchronously, Write may return a nil
  157. // error even though the write failed (or will fail). Always
  158. // use the error returned from Writer.Close to determine if
  159. // the upload was successful.
  160. func (w *Writer) Write(p []byte) (n int, err error) {
  161. w.mu.Lock()
  162. werr := w.err
  163. w.mu.Unlock()
  164. if werr != nil {
  165. return 0, werr
  166. }
  167. if !w.opened {
  168. if err := w.open(); err != nil {
  169. return 0, err
  170. }
  171. }
  172. return w.pw.Write(p)
  173. }
  174. // Close completes the write operation and flushes any buffered data.
  175. // If Close doesn't return an error, metadata about the written object
  176. // can be retrieved by calling Attrs.
  177. func (w *Writer) Close() error {
  178. if !w.opened {
  179. if err := w.open(); err != nil {
  180. return err
  181. }
  182. }
  183. if err := w.pw.Close(); err != nil {
  184. return err
  185. }
  186. <-w.donec
  187. w.mu.Lock()
  188. defer w.mu.Unlock()
  189. return w.err
  190. }
  191. // CloseWithError aborts the write operation with the provided error.
  192. // CloseWithError always returns nil.
  193. //
  194. // Deprecated: cancel the context passed to NewWriter instead.
  195. func (w *Writer) CloseWithError(err error) error {
  196. if !w.opened {
  197. return nil
  198. }
  199. return w.pw.CloseWithError(err)
  200. }
  201. // Attrs returns metadata about a successfully-written object.
  202. // It's only valid to call it after Close returns nil.
  203. func (w *Writer) Attrs() *ObjectAttrs {
  204. return w.obj
  205. }