You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

193 lines
5.6 KiB

  1. package weed_server
  2. import (
  3. "bytes"
  4. "io"
  5. "io/ioutil"
  6. "net/http"
  7. "path"
  8. "strconv"
  9. "time"
  10. "github.com/chrislusf/seaweedfs/weed/filer2"
  11. "github.com/chrislusf/seaweedfs/weed/glog"
  12. "github.com/chrislusf/seaweedfs/weed/operation"
  13. "github.com/chrislusf/seaweedfs/weed/pb/filer_pb"
  14. "github.com/chrislusf/seaweedfs/weed/util"
  15. )
  16. func (fs *FilerServer) autoChunk(w http.ResponseWriter, r *http.Request, replication string, collection string) bool {
  17. if r.Method != "POST" {
  18. glog.V(4).Infoln("AutoChunking not supported for method", r.Method)
  19. return false
  20. }
  21. // autoChunking can be set at the command-line level or as a query param. Query param overrides command-line
  22. query := r.URL.Query()
  23. parsedMaxMB, _ := strconv.ParseInt(query.Get("maxMB"), 10, 32)
  24. maxMB := int32(parsedMaxMB)
  25. if maxMB <= 0 && fs.maxMB > 0 {
  26. maxMB = int32(fs.maxMB)
  27. }
  28. if maxMB <= 0 {
  29. glog.V(4).Infoln("AutoChunking not enabled")
  30. return false
  31. }
  32. glog.V(4).Infoln("AutoChunking level set to", maxMB, "(MB)")
  33. chunkSize := 1024 * 1024 * maxMB
  34. contentLength := int64(0)
  35. if contentLengthHeader := r.Header["Content-Length"]; len(contentLengthHeader) == 1 {
  36. contentLength, _ = strconv.ParseInt(contentLengthHeader[0], 10, 64)
  37. if contentLength <= int64(chunkSize) {
  38. glog.V(4).Infoln("Content-Length of", contentLength, "is less than the chunk size of", chunkSize, "so autoChunking will be skipped.")
  39. return false
  40. }
  41. }
  42. if contentLength <= 0 {
  43. glog.V(4).Infoln("Content-Length value is missing or unexpected so autoChunking will be skipped.")
  44. return false
  45. }
  46. reply, err := fs.doAutoChunk(w, r, contentLength, chunkSize, replication, collection)
  47. if err != nil {
  48. writeJsonError(w, r, http.StatusInternalServerError, err)
  49. } else if reply != nil {
  50. writeJsonQuiet(w, r, http.StatusCreated, reply)
  51. }
  52. return true
  53. }
  54. func (fs *FilerServer) doAutoChunk(w http.ResponseWriter, r *http.Request, contentLength int64, chunkSize int32, replication string, collection string) (filerResult *FilerPostResult, replyerr error) {
  55. multipartReader, multipartReaderErr := r.MultipartReader()
  56. if multipartReaderErr != nil {
  57. return nil, multipartReaderErr
  58. }
  59. part1, part1Err := multipartReader.NextPart()
  60. if part1Err != nil {
  61. return nil, part1Err
  62. }
  63. fileName := part1.FileName()
  64. if fileName != "" {
  65. fileName = path.Base(fileName)
  66. }
  67. var fileChunks []*filer_pb.FileChunk
  68. totalBytesRead := int64(0)
  69. tmpBufferSize := int32(1024 * 1024)
  70. tmpBuffer := bytes.NewBuffer(make([]byte, 0, tmpBufferSize))
  71. chunkBuf := make([]byte, chunkSize+tmpBufferSize, chunkSize+tmpBufferSize) // chunk size plus a little overflow
  72. chunkBufOffset := int32(0)
  73. chunkOffset := int64(0)
  74. writtenChunks := 0
  75. filerResult = &FilerPostResult{
  76. Name: fileName,
  77. }
  78. for totalBytesRead < contentLength {
  79. tmpBuffer.Reset()
  80. bytesRead, readErr := io.CopyN(tmpBuffer, part1, int64(tmpBufferSize))
  81. readFully := readErr != nil && readErr == io.EOF
  82. tmpBuf := tmpBuffer.Bytes()
  83. bytesToCopy := tmpBuf[0:int(bytesRead)]
  84. copy(chunkBuf[chunkBufOffset:chunkBufOffset+int32(bytesRead)], bytesToCopy)
  85. chunkBufOffset = chunkBufOffset + int32(bytesRead)
  86. if chunkBufOffset >= chunkSize || readFully || (chunkBufOffset > 0 && bytesRead == 0) {
  87. writtenChunks = writtenChunks + 1
  88. fileId, urlLocation, assignErr := fs.assignNewFileInfo(w, r, replication, collection)
  89. if assignErr != nil {
  90. return nil, assignErr
  91. }
  92. // upload the chunk to the volume server
  93. chunkName := fileName + "_chunk_" + strconv.FormatInt(int64(len(fileChunks)+1), 10)
  94. uploadErr := fs.doUpload(urlLocation, w, r, chunkBuf[0:chunkBufOffset], chunkName, "application/octet-stream", fileId)
  95. if uploadErr != nil {
  96. return nil, uploadErr
  97. }
  98. // Save to chunk manifest structure
  99. fileChunks = append(fileChunks,
  100. &filer_pb.FileChunk{
  101. FileId: fileId,
  102. Offset: chunkOffset,
  103. Size: uint64(chunkBufOffset),
  104. Mtime: time.Now().UnixNano(),
  105. },
  106. )
  107. // reset variables for the next chunk
  108. chunkBufOffset = 0
  109. chunkOffset = totalBytesRead + int64(bytesRead)
  110. }
  111. totalBytesRead = totalBytesRead + int64(bytesRead)
  112. if bytesRead == 0 || readFully {
  113. break
  114. }
  115. if readErr != nil {
  116. return nil, readErr
  117. }
  118. }
  119. path := r.URL.Path
  120. // also delete the old fid unless PUT operation
  121. if r.Method != "PUT" {
  122. if entry, err := fs.filer.FindEntry(filer2.FullPath(path)); err == nil {
  123. for _, chunk := range entry.Chunks {
  124. oldFid := chunk.FileId
  125. operation.DeleteFile(fs.filer.GetMaster(), oldFid, fs.jwt(oldFid))
  126. }
  127. } else if err != nil {
  128. glog.V(0).Infof("error %v occur when finding %s in filer store", err, path)
  129. }
  130. }
  131. glog.V(4).Infoln("saving", path)
  132. entry := &filer2.Entry{
  133. FullPath: filer2.FullPath(path),
  134. Attr: filer2.Attr{
  135. Mtime: time.Now(),
  136. Crtime: time.Now(),
  137. Mode: 0660,
  138. Replication: replication,
  139. Collection: collection,
  140. TtlSec: int32(util.ParseInt(r.URL.Query().Get("ttl"), 0)),
  141. },
  142. Chunks: fileChunks,
  143. }
  144. if db_err := fs.filer.CreateEntry(entry); db_err != nil {
  145. replyerr = db_err
  146. filerResult.Error = db_err.Error()
  147. glog.V(0).Infof("failing to write %s to filer server : %v", path, db_err)
  148. return
  149. }
  150. return
  151. }
  152. func (fs *FilerServer) doUpload(urlLocation string, w http.ResponseWriter, r *http.Request, chunkBuf []byte, fileName string, contentType string, fileId string) (err error) {
  153. err = nil
  154. ioReader := ioutil.NopCloser(bytes.NewBuffer(chunkBuf))
  155. uploadResult, uploadError := operation.Upload(urlLocation, fileName, ioReader, false, contentType, nil, fs.jwt(fileId))
  156. if uploadResult != nil {
  157. glog.V(0).Infoln("Chunk upload result. Name:", uploadResult.Name, "Fid:", fileId, "Size:", uploadResult.Size)
  158. }
  159. if uploadError != nil {
  160. err = uploadError
  161. }
  162. return
  163. }