uploader.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. package s3util
  2. import (
  3. "bytes"
  4. "encoding/xml"
  5. "github.com/kr/s3"
  6. "fmt"
  7. "io"
  8. "net/http"
  9. "net/url"
  10. "strconv"
  11. "sync"
  12. "syscall"
  13. "time"
  14. )
  15. // defined by amazon
  16. const (
  17. minPartSize = 5 * 1024 * 1024
  18. maxPartSize = 1<<31 - 1 // for 32-bit use; amz max is 5GiB
  19. maxObjSize = 5 * 1024 * 1024 * 1024 * 1024
  20. maxNPart = 10000
  21. )
  22. const (
  23. concurrency = 5
  24. nTry = 2
  25. )
  26. type part struct {
  27. r io.ReadSeeker
  28. len int64
  29. // read by xml encoder
  30. PartNumber int
  31. ETag string
  32. }
  33. type uploader struct {
  34. s3 s3.Service
  35. keys s3.Keys
  36. url string
  37. client *http.Client
  38. UploadId string // written by xml decoder
  39. bufsz int64
  40. buf []byte
  41. off int
  42. ch chan *part
  43. part int
  44. closed bool
  45. err error
  46. wg sync.WaitGroup
  47. xml struct {
  48. XMLName string `xml:"CompleteMultipartUpload"`
  49. Part []*part
  50. }
  51. }
  52. // Create creates an S3 object at url and sends multipart upload requests as
  53. // data is written.
  54. //
  55. // If h is not nil, each of its entries is added to the HTTP request header.
  56. // If c is nil, Create uses DefaultConfig.
  57. func Create(url string, h http.Header, c *Config) (io.WriteCloser, error) {
  58. if c == nil {
  59. c = DefaultConfig
  60. }
  61. return newUploader(url, h, c)
  62. }
  63. // Sends an S3 multipart upload initiation request.
  64. // See http://docs.amazonwebservices.com/AmazonS3/latest/dev/mpuoverview.html.
  65. // This initial request returns an UploadId that we use to identify
  66. // subsequent PUT requests.
  67. func newUploader(url string, h http.Header, c *Config) (u *uploader, err error) {
  68. u = new(uploader)
  69. u.s3 = *c.Service
  70. u.url = url
  71. u.keys = *c.Keys
  72. u.client = c.Client
  73. if u.client == nil {
  74. u.client = http.DefaultClient
  75. }
  76. u.bufsz = minPartSize
  77. r, err := http.NewRequest("POST", url+"?uploads", nil)
  78. if err != nil {
  79. return nil, err
  80. }
  81. r.Header.Set("Date", time.Now().UTC().Format(http.TimeFormat))
  82. for k := range h {
  83. for _, v := range h[k] {
  84. r.Header.Add(k, v)
  85. }
  86. }
  87. u.s3.Sign(r, u.keys)
  88. resp, err := u.client.Do(r)
  89. if err != nil {
  90. return nil, err
  91. }
  92. defer resp.Body.Close()
  93. if resp.StatusCode != 200 {
  94. return nil, newRespError(resp)
  95. }
  96. err = xml.NewDecoder(resp.Body).Decode(u)
  97. if err != nil {
  98. return nil, err
  99. }
  100. u.ch = make(chan *part)
  101. for i := 0; i < concurrency; i++ {
  102. go u.worker()
  103. }
  104. return u, nil
  105. }
  106. func (u *uploader) Write(p []byte) (n int, err error) {
  107. if u.closed {
  108. return 0, syscall.EINVAL
  109. }
  110. if u.err != nil {
  111. return 0, u.err
  112. }
  113. for n < len(p) {
  114. if cap(u.buf) == 0 {
  115. u.buf = make([]byte, int(u.bufsz))
  116. // Increase part size (1.001x).
  117. // This lets us reach the max object size (5TiB) while
  118. // still doing minimal buffering for small objects.
  119. u.bufsz = min(u.bufsz+u.bufsz/1000, maxPartSize)
  120. }
  121. r := copy(u.buf[u.off:], p[n:])
  122. u.off += r
  123. n += r
  124. if u.off == len(u.buf) {
  125. u.flush()
  126. }
  127. }
  128. return n, nil
  129. }
  130. func (u *uploader) flush() {
  131. u.wg.Add(1)
  132. u.part++
  133. p := &part{bytes.NewReader(u.buf[:u.off]), int64(u.off), u.part, ""}
  134. u.xml.Part = append(u.xml.Part, p)
  135. u.ch <- p
  136. u.buf, u.off = nil, 0
  137. }
  138. func (u *uploader) worker() {
  139. for p := range u.ch {
  140. u.retryUploadPart(p)
  141. }
  142. }
  143. // Calls putPart up to nTry times to recover from transient errors.
  144. func (u *uploader) retryUploadPart(p *part) {
  145. defer u.wg.Done()
  146. defer func() { p.r = nil }() // free the large buffer
  147. var err error
  148. for i := 0; i < nTry; i++ {
  149. p.r.Seek(0, 0)
  150. err = u.putPart(p)
  151. if err == nil {
  152. return
  153. }
  154. }
  155. u.err = err
  156. }
  157. // Uploads part p, reading its contents from p.r.
  158. // Stores the ETag in p.ETag.
  159. func (u *uploader) putPart(p *part) error {
  160. v := url.Values{}
  161. v.Set("partNumber", strconv.Itoa(p.PartNumber))
  162. v.Set("uploadId", u.UploadId)
  163. req, err := http.NewRequest("PUT", u.url+"?"+v.Encode(), p.r)
  164. if err != nil {
  165. return err
  166. }
  167. req.ContentLength = p.len
  168. req.Header.Set("Date", time.Now().UTC().Format(http.TimeFormat))
  169. u.s3.Sign(req, u.keys)
  170. resp, err := u.client.Do(req)
  171. if err != nil {
  172. return err
  173. }
  174. defer resp.Body.Close()
  175. if resp.StatusCode != 200 {
  176. return newRespError(resp)
  177. }
  178. s := resp.Header.Get("etag") // includes quote chars for some reason
  179. if len(s) < 2 {
  180. return fmt.Errorf("received invalid etag %q", s)
  181. }
  182. p.ETag = s[1 : len(s)-1]
  183. return nil
  184. }
  185. func (u *uploader) Close() error {
  186. if u.closed {
  187. return syscall.EINVAL
  188. }
  189. if cap(u.buf) > 0 {
  190. u.flush()
  191. }
  192. u.wg.Wait()
  193. close(u.ch)
  194. u.closed = true
  195. if u.err != nil {
  196. u.abort()
  197. return u.err
  198. }
  199. body, err := xml.Marshal(u.xml)
  200. if err != nil {
  201. return err
  202. }
  203. b := bytes.NewBuffer(body)
  204. v := url.Values{}
  205. v.Set("uploadId", u.UploadId)
  206. req, err := http.NewRequest("POST", u.url+"?"+v.Encode(), b)
  207. if err != nil {
  208. return err
  209. }
  210. req.Header.Set("Date", time.Now().UTC().Format(http.TimeFormat))
  211. u.s3.Sign(req, u.keys)
  212. resp, err := u.client.Do(req)
  213. if err != nil {
  214. return err
  215. }
  216. if resp.StatusCode != 200 {
  217. return newRespError(resp)
  218. }
  219. resp.Body.Close()
  220. return nil
  221. }
  222. func (u *uploader) abort() {
  223. // TODO(kr): devise a reasonable way to report an error here in addition
  224. // to the error that caused the abort.
  225. v := url.Values{}
  226. v.Set("uploadId", u.UploadId)
  227. s := u.url + "?" + v.Encode()
  228. req, err := http.NewRequest("DELETE", s, nil)
  229. if err != nil {
  230. return
  231. }
  232. req.Header.Set("Date", time.Now().UTC().Format(http.TimeFormat))
  233. u.s3.Sign(req, u.keys)
  234. resp, err := u.client.Do(req)
  235. if err != nil {
  236. return
  237. }
  238. defer resp.Body.Close()
  239. if resp.StatusCode != 200 {
  240. return
  241. }
  242. }
  243. func min(a, b int64) int64 {
  244. if a < b {
  245. return a
  246. }
  247. return b
  248. }