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.

469 lines
13 KiB

4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
6 months ago
6 months ago
4 years ago
6 months ago
3 years ago
3 years ago
3 years ago
4 years ago
more solid weed mount (#4089) * compare chunks by timestamp * fix slab clearing error * fix test compilation * move oldest chunk to sealed, instead of by fullness * lock on fh.entryViewCache * remove verbose logs * revert slat clearing * less logs * less logs * track write and read by timestamp * remove useless logic * add entry lock on file handle release * use mem chunk only, swap file chunk has problems * comment out code that maybe used later * add debug mode to compare data read and write * more efficient readResolvedChunks with linked list * small optimization * fix test compilation * minor fix on writer * add SeparateGarbageChunks * group chunks into sections * turn off debug mode * fix tests * fix tests * tmp enable swap file chunk * Revert "tmp enable swap file chunk" This reverts commit 985137ec472924e4815f258189f6ca9f2168a0a7. * simple refactoring * simple refactoring * do not re-use swap file chunk. Sealed chunks should not be re-used. * comment out debugging facilities * either mem chunk or swap file chunk is fine now * remove orderedMutex as *semaphore.Weighted not found impactful * optimize size calculation for changing large files * optimize performance to avoid going through the long list of chunks * still problems with swap file chunk * rename * tiny optimization * swap file chunk save only successfully read data * fix * enable both mem and swap file chunk * resolve chunks with range * rename * fix chunk interval list * also change file handle chunk group when adding chunks * pick in-active chunk with time-decayed counter * fix compilation * avoid nil with empty fh.entry * refactoring * rename * rename * refactor visible intervals to *list.List * refactor chunkViews to *list.List * add IntervalList for generic interval list * change visible interval to use IntervalList in generics * cahnge chunkViews to *IntervalList[*ChunkView] * use NewFileChunkSection to create * rename variables * refactor * fix renaming leftover * renaming * renaming * add insert interval * interval list adds lock * incrementally add chunks to readers Fixes: 1. set start and stop offset for the value object 2. clone the value object 3. use pointer instead of copy-by-value when passing to interval.Value 4. use insert interval since adding chunk could be out of order * fix tests compilation * fix tests compilation
2 years ago
more solid weed mount (#4089) * compare chunks by timestamp * fix slab clearing error * fix test compilation * move oldest chunk to sealed, instead of by fullness * lock on fh.entryViewCache * remove verbose logs * revert slat clearing * less logs * less logs * track write and read by timestamp * remove useless logic * add entry lock on file handle release * use mem chunk only, swap file chunk has problems * comment out code that maybe used later * add debug mode to compare data read and write * more efficient readResolvedChunks with linked list * small optimization * fix test compilation * minor fix on writer * add SeparateGarbageChunks * group chunks into sections * turn off debug mode * fix tests * fix tests * tmp enable swap file chunk * Revert "tmp enable swap file chunk" This reverts commit 985137ec472924e4815f258189f6ca9f2168a0a7. * simple refactoring * simple refactoring * do not re-use swap file chunk. Sealed chunks should not be re-used. * comment out debugging facilities * either mem chunk or swap file chunk is fine now * remove orderedMutex as *semaphore.Weighted not found impactful * optimize size calculation for changing large files * optimize performance to avoid going through the long list of chunks * still problems with swap file chunk * rename * tiny optimization * swap file chunk save only successfully read data * fix * enable both mem and swap file chunk * resolve chunks with range * rename * fix chunk interval list * also change file handle chunk group when adding chunks * pick in-active chunk with time-decayed counter * fix compilation * avoid nil with empty fh.entry * refactoring * rename * rename * refactor visible intervals to *list.List * refactor chunkViews to *list.List * add IntervalList for generic interval list * change visible interval to use IntervalList in generics * cahnge chunkViews to *IntervalList[*ChunkView] * use NewFileChunkSection to create * rename variables * refactor * fix renaming leftover * renaming * renaming * add insert interval * interval list adds lock * incrementally add chunks to readers Fixes: 1. set start and stop offset for the value object 2. clone the value object 3. use pointer instead of copy-by-value when passing to interval.Value 4. use insert interval since adding chunk could be out of order * fix tests compilation * fix tests compilation
2 years ago
4 years ago
  1. package weed_server
  2. import (
  3. "bytes"
  4. "context"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "net/http"
  9. "os"
  10. "path"
  11. "strconv"
  12. "strings"
  13. "time"
  14. "github.com/seaweedfs/seaweedfs/weed/filer"
  15. "github.com/seaweedfs/seaweedfs/weed/glog"
  16. "github.com/seaweedfs/seaweedfs/weed/operation"
  17. "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
  18. "github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
  19. "github.com/seaweedfs/seaweedfs/weed/storage/needle"
  20. "github.com/seaweedfs/seaweedfs/weed/util"
  21. )
  22. func (fs *FilerServer) autoChunk(ctx context.Context, w http.ResponseWriter, r *http.Request, contentLength int64, so *operation.StorageOption) {
  23. // autoChunking can be set at the command-line level or as a query param. Query param overrides command-line
  24. query := r.URL.Query()
  25. parsedMaxMB, _ := strconv.ParseInt(query.Get("maxMB"), 10, 32)
  26. maxMB := int32(parsedMaxMB)
  27. if maxMB <= 0 && fs.option.MaxMB > 0 {
  28. maxMB = int32(fs.option.MaxMB)
  29. }
  30. chunkSize := 1024 * 1024 * maxMB
  31. var reply *FilerPostResult
  32. var err error
  33. var md5bytes []byte
  34. if r.Method == http.MethodPost {
  35. if r.Header.Get("Content-Type") == "" && strings.HasSuffix(r.URL.Path, "/") {
  36. reply, err = fs.mkdir(ctx, w, r, so)
  37. } else {
  38. reply, md5bytes, err = fs.doPostAutoChunk(ctx, w, r, chunkSize, contentLength, so)
  39. }
  40. } else {
  41. reply, md5bytes, err = fs.doPutAutoChunk(ctx, w, r, chunkSize, contentLength, so)
  42. }
  43. if err != nil {
  44. if err.Error() == "operation not permitted" {
  45. writeJsonError(w, r, http.StatusForbidden, err)
  46. } else if strings.HasPrefix(err.Error(), "read input:") || err.Error() == io.ErrUnexpectedEOF.Error() {
  47. writeJsonError(w, r, util.HttpStatusCancelled, err)
  48. } else if strings.HasSuffix(err.Error(), "is a file") || strings.HasSuffix(err.Error(), "already exists") {
  49. writeJsonError(w, r, http.StatusConflict, err)
  50. } else {
  51. writeJsonError(w, r, http.StatusInternalServerError, err)
  52. }
  53. } else if reply != nil {
  54. if len(md5bytes) > 0 {
  55. md5InBase64 := util.Base64Encode(md5bytes)
  56. w.Header().Set("Content-MD5", md5InBase64)
  57. }
  58. writeJsonQuiet(w, r, http.StatusCreated, reply)
  59. }
  60. }
  61. func (fs *FilerServer) doPostAutoChunk(ctx context.Context, w http.ResponseWriter, r *http.Request, chunkSize int32, contentLength int64, so *operation.StorageOption) (filerResult *FilerPostResult, md5bytes []byte, replyerr error) {
  62. multipartReader, multipartReaderErr := r.MultipartReader()
  63. if multipartReaderErr != nil {
  64. return nil, nil, multipartReaderErr
  65. }
  66. part1, part1Err := multipartReader.NextPart()
  67. if part1Err != nil {
  68. return nil, nil, part1Err
  69. }
  70. fileName := part1.FileName()
  71. if fileName != "" {
  72. fileName = path.Base(fileName)
  73. }
  74. contentType := part1.Header.Get("Content-Type")
  75. if contentType == "application/octet-stream" {
  76. contentType = ""
  77. }
  78. if err := fs.checkPermissions(ctx, r, fileName); err != nil {
  79. return nil, nil, err
  80. }
  81. if so.SaveInside {
  82. buf := bufPool.Get().(*bytes.Buffer)
  83. buf.Reset()
  84. buf.ReadFrom(part1)
  85. filerResult, replyerr = fs.saveMetaData(ctx, r, fileName, contentType, so, nil, nil, 0, buf.Bytes())
  86. bufPool.Put(buf)
  87. return
  88. }
  89. fileChunks, md5Hash, chunkOffset, err, smallContent := fs.uploadRequestToChunks(w, r, part1, chunkSize, fileName, contentType, contentLength, so)
  90. if err != nil {
  91. return nil, nil, err
  92. }
  93. md5bytes = md5Hash.Sum(nil)
  94. headerMd5 := r.Header.Get("Content-Md5")
  95. if headerMd5 != "" && !(util.Base64Encode(md5bytes) == headerMd5 || fmt.Sprintf("%x", md5bytes) == headerMd5) {
  96. fs.filer.DeleteUncommittedChunks(fileChunks)
  97. return nil, nil, errors.New("The Content-Md5 you specified did not match what we received.")
  98. }
  99. filerResult, replyerr = fs.saveMetaData(ctx, r, fileName, contentType, so, md5bytes, fileChunks, chunkOffset, smallContent)
  100. if replyerr != nil {
  101. fs.filer.DeleteUncommittedChunks(fileChunks)
  102. }
  103. return
  104. }
  105. func (fs *FilerServer) doPutAutoChunk(ctx context.Context, w http.ResponseWriter, r *http.Request, chunkSize int32, contentLength int64, so *operation.StorageOption) (filerResult *FilerPostResult, md5bytes []byte, replyerr error) {
  106. fileName := path.Base(r.URL.Path)
  107. contentType := r.Header.Get("Content-Type")
  108. if contentType == "application/octet-stream" {
  109. contentType = ""
  110. }
  111. if err := fs.checkPermissions(ctx, r, ""); err != nil {
  112. return nil, nil, err
  113. }
  114. fileChunks, md5Hash, chunkOffset, err, smallContent := fs.uploadRequestToChunks(w, r, r.Body, chunkSize, fileName, contentType, contentLength, so)
  115. if err != nil {
  116. return nil, nil, err
  117. }
  118. md5bytes = md5Hash.Sum(nil)
  119. headerMd5 := r.Header.Get("Content-Md5")
  120. if headerMd5 != "" && !(util.Base64Encode(md5bytes) == headerMd5 || fmt.Sprintf("%x", md5bytes) == headerMd5) {
  121. fs.filer.DeleteUncommittedChunks(fileChunks)
  122. return nil, nil, errors.New("The Content-Md5 you specified did not match what we received.")
  123. }
  124. filerResult, replyerr = fs.saveMetaData(ctx, r, fileName, contentType, so, md5bytes, fileChunks, chunkOffset, smallContent)
  125. if replyerr != nil {
  126. fs.filer.DeleteUncommittedChunks(fileChunks)
  127. }
  128. return
  129. }
  130. func isAppend(r *http.Request) bool {
  131. return r.URL.Query().Get("op") == "append"
  132. }
  133. func skipCheckParentDirEntry(r *http.Request) bool {
  134. return r.URL.Query().Get("skipCheckParentDir") == "true"
  135. }
  136. func isS3Request(r *http.Request) bool {
  137. return r.Header.Get(s3_constants.AmzAuthType) != "" || r.Header.Get("X-Amz-Date") != ""
  138. }
  139. func (fs *FilerServer) checkPermissions(ctx context.Context, r *http.Request, fileName string) error {
  140. fullPath := fs.fixFilePath(ctx, r, fileName)
  141. rule := fs.filer.FilerConf.MatchStorageRule(fullPath)
  142. if !rule.Worm {
  143. return nil
  144. }
  145. _, err := fs.filer.FindEntry(ctx, util.FullPath(fullPath))
  146. if err != nil {
  147. if errors.Is(err, filer_pb.ErrNotFound) {
  148. return nil
  149. }
  150. return err
  151. }
  152. // you cannot change an existing file in Worm mode
  153. return errors.New("operation not permitted")
  154. }
  155. func (fs *FilerServer) fixFilePath(ctx context.Context, r *http.Request, fileName string) string {
  156. // fix the path
  157. fullPath := r.URL.Path
  158. if strings.HasSuffix(fullPath, "/") {
  159. if fileName != "" {
  160. fullPath += fileName
  161. }
  162. } else {
  163. if fileName != "" {
  164. if possibleDirEntry, findDirErr := fs.filer.FindEntry(ctx, util.FullPath(fullPath)); findDirErr == nil {
  165. if possibleDirEntry.IsDirectory() {
  166. fullPath += "/" + fileName
  167. }
  168. }
  169. }
  170. }
  171. return fullPath
  172. }
  173. 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) {
  174. // detect file mode
  175. modeStr := r.URL.Query().Get("mode")
  176. if modeStr == "" {
  177. modeStr = "0660"
  178. }
  179. mode, err := strconv.ParseUint(modeStr, 8, 32)
  180. if err != nil {
  181. glog.Errorf("Invalid mode format: %s, use 0660 by default", modeStr)
  182. mode = 0660
  183. }
  184. // fix the path
  185. path := fs.fixFilePath(ctx, r, fileName)
  186. var entry *filer.Entry
  187. var newChunks []*filer_pb.FileChunk
  188. var mergedChunks []*filer_pb.FileChunk
  189. isAppend := isAppend(r)
  190. isOffsetWrite := len(fileChunks) > 0 && fileChunks[0].Offset > 0
  191. // when it is an append
  192. if isAppend || isOffsetWrite {
  193. existingEntry, findErr := fs.filer.FindEntry(ctx, util.FullPath(path))
  194. if findErr != nil && findErr != filer_pb.ErrNotFound {
  195. glog.V(0).Infof("failing to find %s: %v", path, findErr)
  196. }
  197. entry = existingEntry
  198. }
  199. if entry != nil {
  200. entry.Mtime = time.Now()
  201. entry.Md5 = nil
  202. // adjust chunk offsets
  203. if isAppend {
  204. for _, chunk := range fileChunks {
  205. chunk.Offset += int64(entry.FileSize)
  206. }
  207. entry.FileSize += uint64(chunkOffset)
  208. }
  209. newChunks = append(entry.GetChunks(), fileChunks...)
  210. // TODO
  211. if len(entry.Content) > 0 {
  212. replyerr = fmt.Errorf("append to small file is not supported yet")
  213. return
  214. }
  215. } else {
  216. glog.V(4).Infoln("saving", path)
  217. newChunks = fileChunks
  218. entry = &filer.Entry{
  219. FullPath: util.FullPath(path),
  220. Attr: filer.Attr{
  221. Mtime: time.Now(),
  222. Crtime: time.Now(),
  223. Mode: os.FileMode(mode),
  224. Uid: OS_UID,
  225. Gid: OS_GID,
  226. TtlSec: so.TtlSeconds,
  227. Mime: contentType,
  228. Md5: md5bytes,
  229. FileSize: uint64(chunkOffset),
  230. },
  231. Content: content,
  232. }
  233. }
  234. // maybe concatenate small chunks into one whole chunk
  235. mergedChunks, replyerr = fs.maybeMergeChunks(so, newChunks)
  236. if replyerr != nil {
  237. glog.V(0).Infof("merge chunks %s: %v", r.RequestURI, replyerr)
  238. mergedChunks = newChunks
  239. }
  240. // maybe compact entry chunks
  241. mergedChunks, replyerr = filer.MaybeManifestize(fs.saveAsChunk(so), mergedChunks)
  242. if replyerr != nil {
  243. glog.V(0).Infof("manifestize %s: %v", r.RequestURI, replyerr)
  244. return
  245. }
  246. entry.Chunks = mergedChunks
  247. if isOffsetWrite {
  248. entry.Md5 = nil
  249. entry.FileSize = entry.Size()
  250. }
  251. filerResult = &FilerPostResult{
  252. Name: fileName,
  253. Size: int64(entry.FileSize),
  254. }
  255. entry.Extended = SaveAmzMetaData(r, entry.Extended, false)
  256. for k, v := range r.Header {
  257. if len(v) > 0 && len(v[0]) > 0 {
  258. if strings.HasPrefix(k, needle.PairNamePrefix) || k == "Cache-Control" || k == "Expires" || k == "Content-Disposition" {
  259. entry.Extended[k] = []byte(v[0])
  260. }
  261. if k == "Response-Content-Disposition" {
  262. entry.Extended["Content-Disposition"] = []byte(v[0])
  263. }
  264. }
  265. }
  266. dbErr := fs.filer.CreateEntry(ctx, entry, false, false, nil, skipCheckParentDirEntry(r), so.MaxFileNameLength)
  267. // In test_bucket_listv2_delimiter_basic, the valid object key is the parent folder
  268. if dbErr != nil && strings.HasSuffix(dbErr.Error(), " is a file") && isS3Request(r) {
  269. dbErr = fs.filer.CreateEntry(ctx, entry, false, false, nil, true, so.MaxFileNameLength)
  270. }
  271. if dbErr != nil {
  272. replyerr = dbErr
  273. filerResult.Error = dbErr.Error()
  274. glog.V(0).Infof("failing to write %s to filer server : %v", path, dbErr)
  275. }
  276. return filerResult, replyerr
  277. }
  278. func (fs *FilerServer) saveAsChunk(so *operation.StorageOption) filer.SaveDataAsChunkFunctionType {
  279. return func(reader io.Reader, name string, offset int64, tsNs int64) (*filer_pb.FileChunk, error) {
  280. var fileId string
  281. var uploadResult *operation.UploadResult
  282. err := util.Retry("saveAsChunk", func() error {
  283. // assign one file id for one chunk
  284. assignedFileId, urlLocation, auth, assignErr := fs.assignNewFileInfo(so)
  285. if assignErr != nil {
  286. return assignErr
  287. }
  288. fileId = assignedFileId
  289. // upload the chunk to the volume server
  290. uploadOption := &operation.UploadOption{
  291. UploadUrl: urlLocation,
  292. Filename: name,
  293. Cipher: fs.option.Cipher,
  294. IsInputCompressed: false,
  295. MimeType: "",
  296. PairMap: nil,
  297. Jwt: auth,
  298. }
  299. uploader, uploaderErr := operation.NewUploader()
  300. if uploaderErr != nil {
  301. return uploaderErr
  302. }
  303. var uploadErr error
  304. uploadResult, uploadErr, _ = uploader.Upload(reader, uploadOption)
  305. if uploadErr != nil {
  306. return uploadErr
  307. }
  308. return nil
  309. })
  310. if err != nil {
  311. return nil, err
  312. }
  313. return uploadResult.ToPbFileChunk(fileId, offset, tsNs), nil
  314. }
  315. }
  316. func (fs *FilerServer) mkdir(ctx context.Context, w http.ResponseWriter, r *http.Request, so *operation.StorageOption) (filerResult *FilerPostResult, replyerr error) {
  317. // detect file mode
  318. modeStr := r.URL.Query().Get("mode")
  319. if modeStr == "" {
  320. modeStr = "0660"
  321. }
  322. mode, err := strconv.ParseUint(modeStr, 8, 32)
  323. if err != nil {
  324. glog.Errorf("Invalid mode format: %s, use 0660 by default", modeStr)
  325. mode = 0660
  326. }
  327. // fix the path
  328. path := r.URL.Path
  329. if strings.HasSuffix(path, "/") {
  330. path = path[:len(path)-1]
  331. }
  332. existingEntry, err := fs.filer.FindEntry(ctx, util.FullPath(path))
  333. if err == nil && existingEntry != nil {
  334. replyerr = fmt.Errorf("dir %s already exists", path)
  335. return
  336. }
  337. glog.V(4).Infoln("mkdir", path)
  338. entry := &filer.Entry{
  339. FullPath: util.FullPath(path),
  340. Attr: filer.Attr{
  341. Mtime: time.Now(),
  342. Crtime: time.Now(),
  343. Mode: os.FileMode(mode) | os.ModeDir,
  344. Uid: OS_UID,
  345. Gid: OS_GID,
  346. TtlSec: so.TtlSeconds,
  347. },
  348. }
  349. filerResult = &FilerPostResult{
  350. Name: util.FullPath(path).Name(),
  351. }
  352. if dbErr := fs.filer.CreateEntry(ctx, entry, false, false, nil, false, so.MaxFileNameLength); dbErr != nil {
  353. replyerr = dbErr
  354. filerResult.Error = dbErr.Error()
  355. glog.V(0).Infof("failing to create dir %s on filer server : %v", path, dbErr)
  356. }
  357. return filerResult, replyerr
  358. }
  359. func SaveAmzMetaData(r *http.Request, existing map[string][]byte, isReplace bool) (metadata map[string][]byte) {
  360. metadata = make(map[string][]byte)
  361. if !isReplace {
  362. for k, v := range existing {
  363. metadata[k] = v
  364. }
  365. }
  366. if sc := r.Header.Get(s3_constants.AmzStorageClass); sc != "" {
  367. metadata[s3_constants.AmzStorageClass] = []byte(sc)
  368. }
  369. if ce := r.Header.Get("Content-Encoding"); ce != "" {
  370. metadata["Content-Encoding"] = []byte(ce)
  371. }
  372. if tags := r.Header.Get(s3_constants.AmzObjectTagging); tags != "" {
  373. for _, v := range strings.Split(tags, "&") {
  374. tag := strings.Split(v, "=")
  375. if len(tag) == 2 {
  376. metadata[s3_constants.AmzObjectTagging+"-"+tag[0]] = []byte(tag[1])
  377. } else if len(tag) == 1 {
  378. metadata[s3_constants.AmzObjectTagging+"-"+tag[0]] = nil
  379. }
  380. }
  381. }
  382. for header, values := range r.Header {
  383. if strings.HasPrefix(header, s3_constants.AmzUserMetaPrefix) {
  384. for _, value := range values {
  385. metadata[header] = []byte(value)
  386. }
  387. }
  388. }
  389. //acp-owner
  390. acpOwner := r.Header.Get(s3_constants.ExtAmzOwnerKey)
  391. if len(acpOwner) > 0 {
  392. metadata[s3_constants.ExtAmzOwnerKey] = []byte(acpOwner)
  393. }
  394. //acp-grants
  395. acpGrants := r.Header.Get(s3_constants.ExtAmzAclKey)
  396. if len(acpOwner) > 0 {
  397. metadata[s3_constants.ExtAmzAclKey] = []byte(acpGrants)
  398. }
  399. return
  400. }