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.

376 lines
11 KiB

5 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
5 years ago
4 years ago
6 years ago
4 years ago
4 years ago
4 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. xhttp "github.com/chrislusf/seaweedfs/weed/s3api/http"
  20. "github.com/chrislusf/seaweedfs/weed/security"
  21. "github.com/chrislusf/seaweedfs/weed/stats"
  22. "github.com/chrislusf/seaweedfs/weed/storage/needle"
  23. "github.com/chrislusf/seaweedfs/weed/util"
  24. )
  25. func (fs *FilerServer) autoChunk(ctx context.Context, w http.ResponseWriter, r *http.Request, so *operation.StorageOption) {
  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. chunkSize := 1024 * 1024 * maxMB
  34. stats.FilerRequestCounter.WithLabelValues("postAutoChunk").Inc()
  35. start := time.Now()
  36. defer func() {
  37. stats.FilerRequestHistogram.WithLabelValues("postAutoChunk").Observe(time.Since(start).Seconds())
  38. }()
  39. var reply *FilerPostResult
  40. var err error
  41. var md5bytes []byte
  42. if r.Method == "POST" {
  43. if r.Header.Get("Content-Type") == "" && strings.HasSuffix(r.URL.Path, "/") {
  44. reply, err = fs.mkdir(ctx, w, r)
  45. } else {
  46. reply, md5bytes, err = fs.doPostAutoChunk(ctx, w, r, chunkSize, so)
  47. }
  48. } else {
  49. reply, md5bytes, err = fs.doPutAutoChunk(ctx, w, r, chunkSize, so)
  50. }
  51. if err != nil {
  52. if strings.HasPrefix(err.Error(), "read input:") {
  53. writeJsonError(w, r, 499, err)
  54. } else {
  55. writeJsonError(w, r, http.StatusInternalServerError, err)
  56. }
  57. } else if reply != nil {
  58. if len(md5bytes) > 0 {
  59. w.Header().Set("Content-MD5", util.Base64Encode(md5bytes))
  60. }
  61. writeJsonQuiet(w, r, http.StatusCreated, reply)
  62. }
  63. }
  64. func (fs *FilerServer) doPostAutoChunk(ctx context.Context, w http.ResponseWriter, r *http.Request, chunkSize int32, so *operation.StorageOption) (filerResult *FilerPostResult, md5bytes []byte, replyerr error) {
  65. multipartReader, multipartReaderErr := r.MultipartReader()
  66. if multipartReaderErr != nil {
  67. return nil, nil, multipartReaderErr
  68. }
  69. part1, part1Err := multipartReader.NextPart()
  70. if part1Err != nil {
  71. return nil, nil, part1Err
  72. }
  73. fileName := part1.FileName()
  74. if fileName != "" {
  75. fileName = path.Base(fileName)
  76. }
  77. contentType := part1.Header.Get("Content-Type")
  78. if contentType == "application/octet-stream" {
  79. contentType = ""
  80. }
  81. fileChunks, md5Hash, chunkOffset, err, smallContent := fs.uploadReaderToChunks(w, r, part1, chunkSize, fileName, contentType, so)
  82. if err != nil {
  83. return nil, nil, err
  84. }
  85. fileChunks, replyerr = filer.MaybeManifestize(fs.saveAsChunk(so), fileChunks)
  86. if replyerr != nil {
  87. glog.V(0).Infof("manifestize %s: %v", r.RequestURI, replyerr)
  88. return
  89. }
  90. md5bytes = md5Hash.Sum(nil)
  91. filerResult, replyerr = fs.saveMetaData(ctx, r, fileName, contentType, so, md5bytes, fileChunks, chunkOffset, smallContent)
  92. return
  93. }
  94. func (fs *FilerServer) doPutAutoChunk(ctx context.Context, w http.ResponseWriter, r *http.Request, chunkSize int32, so *operation.StorageOption) (filerResult *FilerPostResult, md5bytes []byte, replyerr error) {
  95. fileName := ""
  96. contentType := r.Header.Get("Content-Type")
  97. if contentType == "application/octet-stream" {
  98. contentType = ""
  99. }
  100. fileChunks, md5Hash, chunkOffset, err, smallContent := fs.uploadReaderToChunks(w, r, r.Body, chunkSize, fileName, contentType, so)
  101. if err != nil {
  102. return nil, nil, err
  103. }
  104. fileChunks, replyerr = filer.MaybeManifestize(fs.saveAsChunk(so), fileChunks)
  105. if replyerr != nil {
  106. glog.V(0).Infof("manifestize %s: %v", r.RequestURI, replyerr)
  107. return
  108. }
  109. md5bytes = md5Hash.Sum(nil)
  110. filerResult, replyerr = fs.saveMetaData(ctx, r, fileName, contentType, so, md5bytes, fileChunks, chunkOffset, smallContent)
  111. return
  112. }
  113. func (fs *FilerServer) saveMetaData(ctx context.Context, r *http.Request, fileName string, contentType string, so *operation.StorageOption, md5bytes []byte, fileChunks []*filer_pb.FileChunk, chunkOffset int64, content []byte) (filerResult *FilerPostResult, replyerr error) {
  114. // detect file mode
  115. modeStr := r.URL.Query().Get("mode")
  116. if modeStr == "" {
  117. modeStr = "0660"
  118. }
  119. mode, err := strconv.ParseUint(modeStr, 8, 32)
  120. if err != nil {
  121. glog.Errorf("Invalid mode format: %s, use 0660 by default", modeStr)
  122. mode = 0660
  123. }
  124. // fix the path
  125. path := r.URL.Path
  126. if strings.HasSuffix(path, "/") {
  127. if fileName != "" {
  128. path += fileName
  129. }
  130. }
  131. glog.V(4).Infoln("saving", path)
  132. entry := &filer.Entry{
  133. FullPath: util.FullPath(path),
  134. Attr: filer.Attr{
  135. Mtime: time.Now(),
  136. Crtime: time.Now(),
  137. Mode: os.FileMode(mode),
  138. Uid: OS_UID,
  139. Gid: OS_GID,
  140. Replication: so.Replication,
  141. Collection: so.Collection,
  142. TtlSec: so.TtlSeconds,
  143. Mime: contentType,
  144. Md5: md5bytes,
  145. FileSize: uint64(chunkOffset),
  146. },
  147. Chunks: fileChunks,
  148. Content: content,
  149. }
  150. filerResult = &FilerPostResult{
  151. Name: fileName,
  152. Size: chunkOffset,
  153. }
  154. if entry.Extended == nil {
  155. entry.Extended = make(map[string][]byte)
  156. }
  157. fs.saveAmzMetaData(r, entry)
  158. for k, v := range r.Header {
  159. if len(v) > 0 && strings.HasPrefix(k, needle.PairNamePrefix) {
  160. entry.Extended[k] = []byte(v[0])
  161. }
  162. }
  163. if dbErr := fs.filer.CreateEntry(ctx, entry, false, false, nil); dbErr != nil {
  164. fs.filer.DeleteChunks(entry.Chunks)
  165. replyerr = dbErr
  166. filerResult.Error = dbErr.Error()
  167. glog.V(0).Infof("failing to write %s to filer server : %v", path, dbErr)
  168. }
  169. return filerResult, replyerr
  170. }
  171. func (fs *FilerServer) uploadReaderToChunks(w http.ResponseWriter, r *http.Request, reader io.Reader, chunkSize int32, fileName, contentType string, so *operation.StorageOption) ([]*filer_pb.FileChunk, hash.Hash, int64, error, []byte) {
  172. var fileChunks []*filer_pb.FileChunk
  173. md5Hash := md5.New()
  174. var partReader = ioutil.NopCloser(io.TeeReader(reader, md5Hash))
  175. chunkOffset := int64(0)
  176. var smallContent []byte
  177. for {
  178. limitedReader := io.LimitReader(partReader, int64(chunkSize))
  179. data, err := ioutil.ReadAll(limitedReader)
  180. if err != nil {
  181. return nil, nil, 0, err, nil
  182. }
  183. if chunkOffset == 0 {
  184. if len(data) < fs.option.SaveToFilerLimit || strings.HasPrefix(r.URL.Path, filer.DirectoryEtcRoot) && len(data) < 4*1024 {
  185. smallContent = data
  186. chunkOffset += int64(len(data))
  187. break
  188. }
  189. }
  190. dataReader := util.NewBytesReader(data)
  191. // retry to assign a different file id
  192. var fileId, urlLocation string
  193. var auth security.EncodedJwt
  194. var assignErr, uploadErr error
  195. var uploadResult *operation.UploadResult
  196. for i := 0; i < 3; i++ {
  197. // assign one file id for one chunk
  198. fileId, urlLocation, auth, assignErr = fs.assignNewFileInfo(so)
  199. if assignErr != nil {
  200. return nil, nil, 0, assignErr, nil
  201. }
  202. // upload the chunk to the volume server
  203. uploadResult, uploadErr, _ = fs.doUpload(urlLocation, w, r, dataReader, fileName, contentType, nil, auth)
  204. if uploadErr != nil {
  205. time.Sleep(251 * time.Millisecond)
  206. continue
  207. }
  208. break
  209. }
  210. if uploadErr != nil {
  211. return nil, nil, 0, uploadErr, nil
  212. }
  213. // if last chunk exhausted the reader exactly at the border
  214. if uploadResult.Size == 0 {
  215. break
  216. }
  217. // Save to chunk manifest structure
  218. fileChunks = append(fileChunks, uploadResult.ToPbFileChunk(fileId, chunkOffset))
  219. glog.V(4).Infof("uploaded %s chunk %d to %s [%d,%d)", fileName, len(fileChunks), fileId, chunkOffset, chunkOffset+int64(uploadResult.Size))
  220. // reset variables for the next chunk
  221. chunkOffset = chunkOffset + int64(uploadResult.Size)
  222. // if last chunk was not at full chunk size, but already exhausted the reader
  223. if int64(uploadResult.Size) < int64(chunkSize) {
  224. break
  225. }
  226. }
  227. return fileChunks, md5Hash, chunkOffset, nil, smallContent
  228. }
  229. 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, []byte) {
  230. stats.FilerRequestCounter.WithLabelValues("postAutoChunkUpload").Inc()
  231. start := time.Now()
  232. defer func() {
  233. stats.FilerRequestHistogram.WithLabelValues("postAutoChunkUpload").Observe(time.Since(start).Seconds())
  234. }()
  235. uploadResult, err, data := operation.Upload(urlLocation, fileName, fs.option.Cipher, limitedReader, false, contentType, pairMap, auth)
  236. return uploadResult, err, data
  237. }
  238. func (fs *FilerServer) saveAsChunk(so *operation.StorageOption) filer.SaveDataAsChunkFunctionType {
  239. return func(reader io.Reader, name string, offset int64) (*filer_pb.FileChunk, string, string, error) {
  240. // assign one file id for one chunk
  241. fileId, urlLocation, auth, assignErr := fs.assignNewFileInfo(so)
  242. if assignErr != nil {
  243. return nil, "", "", assignErr
  244. }
  245. // upload the chunk to the volume server
  246. uploadResult, uploadErr, _ := operation.Upload(urlLocation, name, fs.option.Cipher, reader, false, "", nil, auth)
  247. if uploadErr != nil {
  248. return nil, "", "", uploadErr
  249. }
  250. return uploadResult.ToPbFileChunk(fileId, offset), so.Collection, so.Replication, nil
  251. }
  252. }
  253. func (fs *FilerServer) mkdir(ctx context.Context, w http.ResponseWriter, r *http.Request) (filerResult *FilerPostResult, replyerr error) {
  254. // detect file mode
  255. modeStr := r.URL.Query().Get("mode")
  256. if modeStr == "" {
  257. modeStr = "0660"
  258. }
  259. mode, err := strconv.ParseUint(modeStr, 8, 32)
  260. if err != nil {
  261. glog.Errorf("Invalid mode format: %s, use 0660 by default", modeStr)
  262. mode = 0660
  263. }
  264. // fix the path
  265. path := r.URL.Path
  266. if strings.HasSuffix(path, "/") {
  267. path = path[:len(path)-1]
  268. }
  269. existingEntry, err := fs.filer.FindEntry(ctx, util.FullPath(path))
  270. if err == nil && existingEntry != nil {
  271. replyerr = fmt.Errorf("dir %s already exists", path)
  272. return
  273. }
  274. glog.V(4).Infoln("mkdir", path)
  275. entry := &filer.Entry{
  276. FullPath: util.FullPath(path),
  277. Attr: filer.Attr{
  278. Mtime: time.Now(),
  279. Crtime: time.Now(),
  280. Mode: os.FileMode(mode) | os.ModeDir,
  281. Uid: OS_UID,
  282. Gid: OS_GID,
  283. },
  284. }
  285. filerResult = &FilerPostResult{
  286. Name: util.FullPath(path).Name(),
  287. }
  288. if dbErr := fs.filer.CreateEntry(ctx, entry, false, false, nil); dbErr != nil {
  289. replyerr = dbErr
  290. filerResult.Error = dbErr.Error()
  291. glog.V(0).Infof("failing to create dir %s on filer server : %v", path, dbErr)
  292. }
  293. return filerResult, replyerr
  294. }
  295. func (fs *FilerServer) saveAmzMetaData(r *http.Request, entry *filer.Entry) {
  296. if sc := r.Header.Get(xhttp.AmzStorageClass); sc != "" {
  297. entry.Extended[xhttp.AmzStorageClass] = []byte(sc)
  298. }
  299. if tags := r.Header.Get(xhttp.AmzObjectTagging); tags != "" {
  300. for _, v := range strings.Split(tags, "&") {
  301. tag := strings.Split(v, "=")
  302. if len(tag) == 2 {
  303. entry.Extended[xhttp.AmzObjectTagging+"-"+tag[0]] = []byte(tag[1])
  304. }
  305. }
  306. }
  307. for header, values := range r.Header {
  308. if strings.HasPrefix(header, xhttp.AmzUserMetaPrefix) {
  309. for _, value := range values {
  310. entry.Extended[header] = []byte(value)
  311. }
  312. }
  313. }
  314. }