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.

191 lines
5.5 KiB

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