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.

310 lines
10 KiB

5 years ago
5 years ago
6 years ago
5 years ago
4 years ago
  1. package weed_server
  2. import (
  3. "context"
  4. "crypto/md5"
  5. "fmt"
  6. "hash"
  7. "io"
  8. "io/ioutil"
  9. "net/http"
  10. "os"
  11. "path"
  12. "strconv"
  13. "strings"
  14. "time"
  15. "github.com/chrislusf/seaweedfs/weed/filer"
  16. "github.com/chrislusf/seaweedfs/weed/glog"
  17. "github.com/chrislusf/seaweedfs/weed/operation"
  18. "github.com/chrislusf/seaweedfs/weed/pb/filer_pb"
  19. "github.com/chrislusf/seaweedfs/weed/security"
  20. "github.com/chrislusf/seaweedfs/weed/stats"
  21. "github.com/chrislusf/seaweedfs/weed/util"
  22. )
  23. func (fs *FilerServer) autoChunk(ctx context.Context, w http.ResponseWriter, r *http.Request, replication string, collection string, dataCenter string, rack string, ttlSec int32, ttlString string, fsync bool) {
  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. chunkSize := 1024 * 1024 * maxMB
  32. stats.FilerRequestCounter.WithLabelValues("postAutoChunk").Inc()
  33. start := time.Now()
  34. defer func() {
  35. stats.FilerRequestHistogram.WithLabelValues("postAutoChunk").Observe(time.Since(start).Seconds())
  36. }()
  37. var reply *FilerPostResult
  38. var err error
  39. var md5bytes []byte
  40. if r.Method == "POST" {
  41. if r.Header.Get("Content-Type") == "" && strings.HasSuffix(r.URL.Path, "/") {
  42. reply, err = fs.mkdir(ctx, w, r)
  43. } else {
  44. reply, md5bytes, err = fs.doPostAutoChunk(ctx, w, r, chunkSize, replication, collection, dataCenter, rack, ttlSec, ttlString, fsync)
  45. }
  46. } else {
  47. reply, md5bytes, err = fs.doPutAutoChunk(ctx, w, r, chunkSize, replication, collection, dataCenter, rack, ttlSec, ttlString, fsync)
  48. }
  49. if err != nil {
  50. writeJsonError(w, r, http.StatusInternalServerError, err)
  51. } else if reply != nil {
  52. if len(md5bytes) > 0 {
  53. w.Header().Set("Content-MD5", util.Base64Encode(md5bytes))
  54. }
  55. writeJsonQuiet(w, r, http.StatusCreated, reply)
  56. }
  57. }
  58. func (fs *FilerServer) doPostAutoChunk(ctx context.Context, w http.ResponseWriter, r *http.Request, chunkSize int32, replication string, collection string, dataCenter string, rack string, ttlSec int32, ttlString string, fsync bool) (filerResult *FilerPostResult, md5bytes []byte, replyerr error) {
  59. multipartReader, multipartReaderErr := r.MultipartReader()
  60. if multipartReaderErr != nil {
  61. return nil, nil, multipartReaderErr
  62. }
  63. part1, part1Err := multipartReader.NextPart()
  64. if part1Err != nil {
  65. return nil, nil, part1Err
  66. }
  67. fileName := part1.FileName()
  68. if fileName != "" {
  69. fileName = path.Base(fileName)
  70. }
  71. contentType := part1.Header.Get("Content-Type")
  72. if contentType == "application/octet-stream" {
  73. contentType = ""
  74. }
  75. fileChunks, md5Hash, chunkOffset, err := fs.uploadReaderToChunks(w, r, part1, chunkSize, replication, collection, dataCenter, rack, ttlString, fileName, contentType, fsync)
  76. if err != nil {
  77. return nil, nil, err
  78. }
  79. fileChunks, replyerr = filer.MaybeManifestize(fs.saveAsChunk(replication, collection, dataCenter, rack, ttlString, fsync), fileChunks)
  80. if replyerr != nil {
  81. glog.V(0).Infof("manifestize %s: %v", r.RequestURI, replyerr)
  82. return
  83. }
  84. md5bytes = md5Hash.Sum(nil)
  85. filerResult, replyerr = fs.saveMetaData(ctx, r, fileName, replication, collection, ttlSec, contentType, md5bytes, fileChunks, chunkOffset)
  86. return
  87. }
  88. func (fs *FilerServer) doPutAutoChunk(ctx context.Context, w http.ResponseWriter, r *http.Request, chunkSize int32, replication string, collection string, dataCenter string, rack string, ttlSec int32, ttlString string, fsync bool) (filerResult *FilerPostResult, md5bytes []byte, replyerr error) {
  89. fileName := ""
  90. contentType := ""
  91. fileChunks, md5Hash, chunkOffset, err := fs.uploadReaderToChunks(w, r, r.Body, chunkSize, replication, collection, dataCenter, rack, ttlString, fileName, contentType, fsync)
  92. if err != nil {
  93. return nil, nil, err
  94. }
  95. fileChunks, replyerr = filer.MaybeManifestize(fs.saveAsChunk(replication, collection, dataCenter, rack, ttlString, fsync), fileChunks)
  96. if replyerr != nil {
  97. glog.V(0).Infof("manifestize %s: %v", r.RequestURI, replyerr)
  98. return
  99. }
  100. md5bytes = md5Hash.Sum(nil)
  101. filerResult, replyerr = fs.saveMetaData(ctx, r, fileName, replication, collection, ttlSec, contentType, md5bytes, fileChunks, chunkOffset)
  102. return
  103. }
  104. func (fs *FilerServer) saveMetaData(ctx context.Context, r *http.Request, fileName string, replication string, collection string, ttlSec int32, contentType string, md5bytes []byte, fileChunks []*filer_pb.FileChunk, chunkOffset int64) (filerResult *FilerPostResult, replyerr error) {
  105. // detect file mode
  106. modeStr := r.URL.Query().Get("mode")
  107. if modeStr == "" {
  108. modeStr = "0660"
  109. }
  110. mode, err := strconv.ParseUint(modeStr, 8, 32)
  111. if err != nil {
  112. glog.Errorf("Invalid mode format: %s, use 0660 by default", modeStr)
  113. mode = 0660
  114. }
  115. // fix the path
  116. path := r.URL.Path
  117. if strings.HasSuffix(path, "/") {
  118. if fileName != "" {
  119. path += fileName
  120. }
  121. }
  122. // fix the crTime
  123. existingEntry, err := fs.filer.FindEntry(ctx, util.FullPath(path))
  124. crTime := time.Now()
  125. if err == nil && existingEntry != nil {
  126. crTime = existingEntry.Crtime
  127. }
  128. glog.V(4).Infoln("saving", path)
  129. entry := &filer.Entry{
  130. FullPath: util.FullPath(path),
  131. Attr: filer.Attr{
  132. Mtime: time.Now(),
  133. Crtime: crTime,
  134. Mode: os.FileMode(mode),
  135. Uid: OS_UID,
  136. Gid: OS_GID,
  137. Replication: replication,
  138. Collection: collection,
  139. TtlSec: ttlSec,
  140. Mime: contentType,
  141. Md5: md5bytes,
  142. FileSize: uint64(chunkOffset),
  143. },
  144. Chunks: fileChunks,
  145. }
  146. filerResult = &FilerPostResult{
  147. Name: fileName,
  148. Size: chunkOffset,
  149. }
  150. if dbErr := fs.filer.CreateEntry(ctx, entry, false, false, nil); dbErr != nil {
  151. fs.filer.DeleteChunks(entry.Chunks)
  152. replyerr = dbErr
  153. filerResult.Error = dbErr.Error()
  154. glog.V(0).Infof("failing to write %s to filer server : %v", path, dbErr)
  155. }
  156. return filerResult, replyerr
  157. }
  158. func (fs *FilerServer) uploadReaderToChunks(w http.ResponseWriter, r *http.Request, reader io.Reader, chunkSize int32, replication string, collection string, dataCenter string, rack string, ttlString string, fileName string, contentType string, fsync bool) ([]*filer_pb.FileChunk, hash.Hash, int64, error) {
  159. var fileChunks []*filer_pb.FileChunk
  160. md5Hash := md5.New()
  161. var partReader = ioutil.NopCloser(io.TeeReader(reader, md5Hash))
  162. chunkOffset := int64(0)
  163. for {
  164. limitedReader := io.LimitReader(partReader, int64(chunkSize))
  165. // assign one file id for one chunk
  166. fileId, urlLocation, auth, assignErr := fs.assignNewFileInfo(replication, collection, dataCenter, rack, ttlString, fsync)
  167. if assignErr != nil {
  168. return nil, nil, 0, assignErr
  169. }
  170. // upload the chunk to the volume server
  171. uploadResult, uploadErr := fs.doUpload(urlLocation, w, r, limitedReader, fileName, contentType, nil, auth)
  172. if uploadErr != nil {
  173. return nil, nil, 0, uploadErr
  174. }
  175. // if last chunk exhausted the reader exactly at the border
  176. if uploadResult.Size == 0 {
  177. break
  178. }
  179. // Save to chunk manifest structure
  180. fileChunks = append(fileChunks, uploadResult.ToPbFileChunk(fileId, chunkOffset))
  181. glog.V(4).Infof("uploaded %s chunk %d to %s [%d,%d)", fileName, len(fileChunks), fileId, chunkOffset, chunkOffset+int64(uploadResult.Size))
  182. // reset variables for the next chunk
  183. chunkOffset = chunkOffset + int64(uploadResult.Size)
  184. // if last chunk was not at full chunk size, but already exhausted the reader
  185. if int64(uploadResult.Size) < int64(chunkSize) {
  186. break
  187. }
  188. }
  189. return fileChunks, md5Hash, chunkOffset, nil
  190. }
  191. 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) {
  192. stats.FilerRequestCounter.WithLabelValues("postAutoChunkUpload").Inc()
  193. start := time.Now()
  194. defer func() {
  195. stats.FilerRequestHistogram.WithLabelValues("postAutoChunkUpload").Observe(time.Since(start).Seconds())
  196. }()
  197. uploadResult, err, _ := operation.Upload(urlLocation, fileName, fs.option.Cipher, limitedReader, false, contentType, pairMap, auth)
  198. return uploadResult, err
  199. }
  200. func (fs *FilerServer) saveAsChunk(replication string, collection string, dataCenter string, rack string, ttlString string, fsync bool) filer.SaveDataAsChunkFunctionType {
  201. return func(reader io.Reader, name string, offset int64) (*filer_pb.FileChunk, string, string, error) {
  202. // assign one file id for one chunk
  203. fileId, urlLocation, auth, assignErr := fs.assignNewFileInfo(replication, collection, dataCenter, rack, ttlString, fsync)
  204. if assignErr != nil {
  205. return nil, "", "", assignErr
  206. }
  207. // upload the chunk to the volume server
  208. uploadResult, uploadErr, _ := operation.Upload(urlLocation, name, fs.option.Cipher, reader, false, "", nil, auth)
  209. if uploadErr != nil {
  210. return nil, "", "", uploadErr
  211. }
  212. return uploadResult.ToPbFileChunk(fileId, offset), collection, replication, nil
  213. }
  214. }
  215. func (fs *FilerServer) mkdir(ctx context.Context, w http.ResponseWriter, r *http.Request) (filerResult *FilerPostResult, replyerr error) {
  216. // detect file mode
  217. modeStr := r.URL.Query().Get("mode")
  218. if modeStr == "" {
  219. modeStr = "0660"
  220. }
  221. mode, err := strconv.ParseUint(modeStr, 8, 32)
  222. if err != nil {
  223. glog.Errorf("Invalid mode format: %s, use 0660 by default", modeStr)
  224. mode = 0660
  225. }
  226. // fix the path
  227. path := r.URL.Path
  228. if strings.HasSuffix(path, "/") {
  229. path = path[:len(path)-1]
  230. }
  231. existingEntry, err := fs.filer.FindEntry(ctx, util.FullPath(path))
  232. if err == nil && existingEntry != nil {
  233. replyerr = fmt.Errorf("dir %s already exists", path)
  234. return
  235. }
  236. glog.V(4).Infoln("mkdir", path)
  237. entry := &filer.Entry{
  238. FullPath: util.FullPath(path),
  239. Attr: filer.Attr{
  240. Mtime: time.Now(),
  241. Crtime: time.Now(),
  242. Mode: os.FileMode(mode) | os.ModeDir,
  243. Uid: OS_UID,
  244. Gid: OS_GID,
  245. },
  246. }
  247. filerResult = &FilerPostResult{
  248. Name: util.FullPath(path).Name(),
  249. }
  250. if dbErr := fs.filer.CreateEntry(ctx, entry, false, false, nil); dbErr != nil {
  251. replyerr = dbErr
  252. filerResult.Error = dbErr.Error()
  253. glog.V(0).Infof("failing to create dir %s on filer server : %v", path, dbErr)
  254. }
  255. return filerResult, replyerr
  256. }