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.

212 lines
6.6 KiB

5 years ago
6 years ago
6 years ago
6 years ago
5 years ago
6 years ago
5 years ago
  1. package weed_server
  2. import (
  3. "context"
  4. "crypto/md5"
  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/stats"
  18. "github.com/chrislusf/seaweedfs/weed/util"
  19. )
  20. func (fs *FilerServer) autoChunk(ctx context.Context, w http.ResponseWriter, r *http.Request,
  21. replication string, collection string, dataCenter string, ttlSec int32, ttlString string, fsync bool) bool {
  22. if r.Method != "POST" {
  23. glog.V(4).Infoln("AutoChunking not supported for method", r.Method)
  24. return false
  25. }
  26. // autoChunking can be set at the command-line level or as a query param. Query param overrides command-line
  27. query := r.URL.Query()
  28. parsedMaxMB, _ := strconv.ParseInt(query.Get("maxMB"), 10, 32)
  29. maxMB := int32(parsedMaxMB)
  30. if maxMB <= 0 && fs.option.MaxMB > 0 {
  31. maxMB = int32(fs.option.MaxMB)
  32. }
  33. if maxMB <= 0 {
  34. glog.V(4).Infoln("AutoChunking not enabled")
  35. return false
  36. }
  37. glog.V(4).Infoln("AutoChunking level set to", maxMB, "(MB)")
  38. chunkSize := 1024 * 1024 * maxMB
  39. contentLength := int64(0)
  40. if contentLengthHeader := r.Header["Content-Length"]; len(contentLengthHeader) == 1 {
  41. contentLength, _ = strconv.ParseInt(contentLengthHeader[0], 10, 64)
  42. if contentLength <= int64(chunkSize) {
  43. glog.V(4).Infoln("Content-Length of", contentLength, "is less than the chunk size of", chunkSize, "so autoChunking will be skipped.")
  44. return false
  45. }
  46. }
  47. if contentLength <= 0 {
  48. glog.V(4).Infoln("Content-Length value is missing or unexpected so autoChunking will be skipped.")
  49. return false
  50. }
  51. reply, err := fs.doAutoChunk(ctx, w, r, contentLength, chunkSize, replication, collection, dataCenter, ttlSec, ttlString, fsync)
  52. if err != nil {
  53. writeJsonError(w, r, http.StatusInternalServerError, err)
  54. } else if reply != nil {
  55. writeJsonQuiet(w, r, http.StatusCreated, reply)
  56. }
  57. return true
  58. }
  59. func (fs *FilerServer) doAutoChunk(ctx context.Context, w http.ResponseWriter, r *http.Request,
  60. contentLength int64, chunkSize int32, replication string, collection string, dataCenter string, ttlSec int32, ttlString string, fsync bool) (filerResult *FilerPostResult, replyerr error) {
  61. stats.FilerRequestCounter.WithLabelValues("postAutoChunk").Inc()
  62. start := time.Now()
  63. defer func() {
  64. stats.FilerRequestHistogram.WithLabelValues("postAutoChunk").Observe(time.Since(start).Seconds())
  65. }()
  66. multipartReader, multipartReaderErr := r.MultipartReader()
  67. if multipartReaderErr != nil {
  68. return nil, multipartReaderErr
  69. }
  70. part1, part1Err := multipartReader.NextPart()
  71. if part1Err != nil {
  72. return nil, part1Err
  73. }
  74. fileName := part1.FileName()
  75. if fileName != "" {
  76. fileName = path.Base(fileName)
  77. }
  78. contentType := part1.Header.Get("Content-Type")
  79. var fileChunks []*filer_pb.FileChunk
  80. md5Hash := md5.New()
  81. var partReader = ioutil.NopCloser(io.TeeReader(part1, md5Hash))
  82. chunkOffset := int64(0)
  83. for chunkOffset < contentLength {
  84. limitedReader := io.LimitReader(partReader, int64(chunkSize))
  85. // assign one file id for one chunk
  86. fileId, urlLocation, auth, assignErr := fs.assignNewFileInfo(replication, collection, dataCenter, ttlString, fsync)
  87. if assignErr != nil {
  88. return nil, assignErr
  89. }
  90. // upload the chunk to the volume server
  91. uploadResult, uploadErr := fs.doUpload(urlLocation, w, r, limitedReader, fileName, contentType, nil, auth)
  92. if uploadErr != nil {
  93. return nil, uploadErr
  94. }
  95. // if last chunk exhausted the reader exactly at the border
  96. if uploadResult.Size == 0 {
  97. break
  98. }
  99. // Save to chunk manifest structure
  100. fileChunks = append(fileChunks, uploadResult.ToPbFileChunk(fileId, chunkOffset))
  101. glog.V(4).Infof("uploaded %s chunk %d to %s [%d,%d) of %d", fileName, len(fileChunks), fileId, chunkOffset, chunkOffset+int64(uploadResult.Size), contentLength)
  102. // reset variables for the next chunk
  103. chunkOffset = chunkOffset + int64(uploadResult.Size)
  104. // if last chunk was not at full chunk size, but already exhausted the reader
  105. if int64(uploadResult.Size) < int64(chunkSize) {
  106. break
  107. }
  108. }
  109. fileChunks, replyerr = filer2.MaybeManifestize(fs.saveAsChunk(replication, collection, dataCenter, ttlString, fsync), fileChunks)
  110. if replyerr != nil {
  111. glog.V(0).Infof("manifestize %s: %v", r.RequestURI, replyerr)
  112. return
  113. }
  114. path := r.URL.Path
  115. if strings.HasSuffix(path, "/") {
  116. if fileName != "" {
  117. path += fileName
  118. }
  119. }
  120. glog.V(4).Infoln("saving", path)
  121. entry := &filer2.Entry{
  122. FullPath: util.FullPath(path),
  123. Attr: filer2.Attr{
  124. Mtime: time.Now(),
  125. Crtime: time.Now(),
  126. Mode: 0660,
  127. Uid: OS_UID,
  128. Gid: OS_GID,
  129. Replication: replication,
  130. Collection: collection,
  131. TtlSec: ttlSec,
  132. Mime: contentType,
  133. Md5: md5Hash.Sum(nil),
  134. },
  135. Chunks: fileChunks,
  136. }
  137. filerResult = &FilerPostResult{
  138. Name: fileName,
  139. Size: chunkOffset,
  140. }
  141. if dbErr := fs.filer.CreateEntry(ctx, entry, false, false); dbErr != nil {
  142. fs.filer.DeleteChunks(entry.Chunks)
  143. replyerr = dbErr
  144. filerResult.Error = dbErr.Error()
  145. glog.V(0).Infof("failing to write %s to filer server : %v", path, dbErr)
  146. return
  147. }
  148. return
  149. }
  150. func (fs *FilerServer) doUpload(urlLocation string, w http.ResponseWriter, r *http.Request, limitedReader io.Reader, fileName string, contentType string, pairMap map[string]string, auth security.EncodedJwt) (*operation.UploadResult, error) {
  151. stats.FilerRequestCounter.WithLabelValues("postAutoChunkUpload").Inc()
  152. start := time.Now()
  153. defer func() {
  154. stats.FilerRequestHistogram.WithLabelValues("postAutoChunkUpload").Observe(time.Since(start).Seconds())
  155. }()
  156. uploadResult, err, _ := operation.Upload(urlLocation, fileName, fs.option.Cipher, limitedReader, false, contentType, pairMap, auth)
  157. return uploadResult, err
  158. }
  159. func (fs *FilerServer) saveAsChunk(replication string, collection string, dataCenter string, ttlString string, fsync bool) filer2.SaveDataAsChunkFunctionType {
  160. return func(reader io.Reader, name string, offset int64) (*filer_pb.FileChunk, string, string, error) {
  161. // assign one file id for one chunk
  162. fileId, urlLocation, auth, assignErr := fs.assignNewFileInfo(replication, collection, dataCenter, ttlString, fsync)
  163. if assignErr != nil {
  164. return nil, "", "", assignErr
  165. }
  166. // upload the chunk to the volume server
  167. uploadResult, uploadErr, _ := operation.Upload(urlLocation, name, fs.option.Cipher, reader, false, "", nil, auth)
  168. if uploadErr != nil {
  169. return nil, "", "", uploadErr
  170. }
  171. return uploadResult.ToPbFileChunk(fileId, offset), collection, replication, nil
  172. }
  173. }