writer.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  1. // Copyright 2014 Google Inc. All Rights Reserved.
  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. "unicode/utf8"
  21. "golang.org/x/net/context"
  22. "google.golang.org/api/googleapi"
  23. raw "google.golang.org/api/storage/v1"
  24. )
  25. // A Writer writes a Cloud Storage object.
  26. type Writer struct {
  27. // ObjectAttrs are optional attributes to set on the object. Any attributes
  28. // must be initialized before the first Write call. Nil or zero-valued
  29. // attributes are ignored.
  30. ObjectAttrs
  31. // SendCRC specifies whether to transmit a CRC32C field. It should be set
  32. // to true in addition to setting the Writer's CRC32C field, because zero
  33. // is a valid CRC and normally a zero would not be transmitted.
  34. SendCRC32C bool
  35. // ChunkSize controls the maximum number of bytes of the object that the
  36. // Writer will attempt to send to the server in a single request. Objects
  37. // smaller than the size will be sent in a single request, while larger
  38. // objects will be split over multiple requests. The size will be rounded up
  39. // to the nearest multiple of 256K. If zero, chunking will be disabled and
  40. // the object will be uploaded in a single request.
  41. //
  42. // ChunkSize will default to a reasonable value. Any custom configuration
  43. // must be done before the first Write call.
  44. ChunkSize int
  45. // ProgressFunc can be used to monitor the progress of a large write.
  46. // operation. If ProgressFunc is not nil and writing requires multiple
  47. // calls to the underlying service (see
  48. // https://cloud.google.com/storage/docs/json_api/v1/how-tos/resumable-upload),
  49. // then ProgressFunc will be invoked after each call with the number of bytes of
  50. // content copied so far.
  51. //
  52. // ProgressFunc should return quickly without blocking.
  53. ProgressFunc func(int64)
  54. ctx context.Context
  55. o *ObjectHandle
  56. opened bool
  57. pw *io.PipeWriter
  58. donec chan struct{} // closed after err and obj are set.
  59. err error
  60. obj *ObjectAttrs
  61. }
  62. func (w *Writer) open() error {
  63. attrs := w.ObjectAttrs
  64. // Check the developer didn't change the object Name (this is unfortunate, but
  65. // we don't want to store an object under the wrong name).
  66. if attrs.Name != w.o.object {
  67. return fmt.Errorf("storage: Writer.Name %q does not match object name %q", attrs.Name, w.o.object)
  68. }
  69. if !utf8.ValidString(attrs.Name) {
  70. return fmt.Errorf("storage: object name %q is not valid UTF-8", attrs.Name)
  71. }
  72. pr, pw := io.Pipe()
  73. w.pw = pw
  74. w.opened = true
  75. if w.ChunkSize < 0 {
  76. return errors.New("storage: Writer.ChunkSize must non-negative")
  77. }
  78. mediaOpts := []googleapi.MediaOption{
  79. googleapi.ChunkSize(w.ChunkSize),
  80. }
  81. if c := attrs.ContentType; c != "" {
  82. mediaOpts = append(mediaOpts, googleapi.ContentType(c))
  83. }
  84. go func() {
  85. defer close(w.donec)
  86. rawObj := attrs.toRawObject(w.o.bucket)
  87. if w.SendCRC32C {
  88. rawObj.Crc32c = encodeUint32(attrs.CRC32C)
  89. }
  90. if w.MD5 != nil {
  91. rawObj.Md5Hash = base64.StdEncoding.EncodeToString(w.MD5)
  92. }
  93. call := w.o.c.raw.Objects.Insert(w.o.bucket, rawObj).
  94. Media(pr, mediaOpts...).
  95. Projection("full").
  96. Context(w.ctx)
  97. if w.ProgressFunc != nil {
  98. call.ProgressUpdater(func(n, _ int64) { w.ProgressFunc(n) })
  99. }
  100. if err := setEncryptionHeaders(call.Header(), w.o.encryptionKey, false); err != nil {
  101. w.err = err
  102. pr.CloseWithError(w.err)
  103. return
  104. }
  105. var resp *raw.Object
  106. err := applyConds("NewWriter", w.o.gen, w.o.conds, call)
  107. if err == nil {
  108. if w.o.userProject != "" {
  109. call.UserProject(w.o.userProject)
  110. }
  111. setClientHeader(call.Header())
  112. // We will only retry here if the initial POST, which obtains a URI for
  113. // the resumable upload, fails with a retryable error. The upload itself
  114. // has its own retry logic.
  115. err = runWithRetry(w.ctx, func() error {
  116. var err2 error
  117. resp, err2 = call.Do()
  118. return err2
  119. })
  120. }
  121. if err != nil {
  122. w.err = err
  123. pr.CloseWithError(w.err)
  124. return
  125. }
  126. w.obj = newObject(resp)
  127. }()
  128. return nil
  129. }
  130. // Write appends to w. It implements the io.Writer interface.
  131. //
  132. // Since writes happen asynchronously, Write may return a nil
  133. // error even though the write failed (or will fail). Always
  134. // use the error returned from Writer.Close to determine if
  135. // the upload was successful.
  136. func (w *Writer) Write(p []byte) (n int, err error) {
  137. if w.err != nil {
  138. return 0, w.err
  139. }
  140. if !w.opened {
  141. if err := w.open(); err != nil {
  142. return 0, err
  143. }
  144. }
  145. return w.pw.Write(p)
  146. }
  147. // Close completes the write operation and flushes any buffered data.
  148. // If Close doesn't return an error, metadata about the written object
  149. // can be retrieved by calling Attrs.
  150. func (w *Writer) Close() error {
  151. if !w.opened {
  152. if err := w.open(); err != nil {
  153. return err
  154. }
  155. }
  156. if err := w.pw.Close(); err != nil {
  157. return err
  158. }
  159. <-w.donec
  160. return w.err
  161. }
  162. // CloseWithError aborts the write operation with the provided error.
  163. // CloseWithError always returns nil.
  164. func (w *Writer) CloseWithError(err error) error {
  165. if !w.opened {
  166. return nil
  167. }
  168. return w.pw.CloseWithError(err)
  169. }
  170. // Attrs returns metadata about a successfully-written object.
  171. // It's only valid to call it after Close returns nil.
  172. func (w *Writer) Attrs() *ObjectAttrs {
  173. return w.obj
  174. }