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.

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