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.

192 lines
5.6 KiB

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