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.

311 lines
10 KiB

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