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.

422 lines
12 KiB

4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years 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. //"github.com/seaweedfs/seaweedfs/weed/s3api"
  8. "github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
  9. "io"
  10. "net/http"
  11. "os"
  12. "path"
  13. "strconv"
  14. "strings"
  15. "time"
  16. "github.com/seaweedfs/seaweedfs/weed/filer"
  17. "github.com/seaweedfs/seaweedfs/weed/glog"
  18. "github.com/seaweedfs/seaweedfs/weed/operation"
  19. "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
  20. "github.com/seaweedfs/seaweedfs/weed/storage/needle"
  21. "github.com/seaweedfs/seaweedfs/weed/util"
  22. )
  23. func (fs *FilerServer) autoChunk(ctx context.Context, w http.ResponseWriter, r *http.Request, contentLength int64, so *operation.StorageOption) {
  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. var reply *FilerPostResult
  33. var err error
  34. var md5bytes []byte
  35. if r.Method == "POST" {
  36. if r.Header.Get("Content-Type") == "" && strings.HasSuffix(r.URL.Path, "/") {
  37. reply, err = fs.mkdir(ctx, w, r, so)
  38. } else {
  39. reply, md5bytes, err = fs.doPostAutoChunk(ctx, w, r, chunkSize, contentLength, so)
  40. }
  41. } else {
  42. reply, md5bytes, err = fs.doPutAutoChunk(ctx, w, r, chunkSize, contentLength, so)
  43. }
  44. if err != nil {
  45. if strings.HasPrefix(err.Error(), "read input:") || err.Error() == io.ErrUnexpectedEOF.Error() {
  46. writeJsonError(w, r, util.HttpStatusCancelled, err)
  47. } else if strings.HasSuffix(err.Error(), "is a file") || strings.HasSuffix(err.Error(), "already exists") {
  48. writeJsonError(w, r, http.StatusConflict, err)
  49. } else {
  50. writeJsonError(w, r, http.StatusInternalServerError, err)
  51. }
  52. } else if reply != nil {
  53. if len(md5bytes) > 0 {
  54. md5InBase64 := util.Base64Encode(md5bytes)
  55. w.Header().Set("Content-MD5", md5InBase64)
  56. }
  57. writeJsonQuiet(w, r, http.StatusCreated, reply)
  58. }
  59. }
  60. 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) {
  61. multipartReader, multipartReaderErr := r.MultipartReader()
  62. if multipartReaderErr != nil {
  63. return nil, nil, multipartReaderErr
  64. }
  65. part1, part1Err := multipartReader.NextPart()
  66. if part1Err != nil {
  67. return nil, nil, part1Err
  68. }
  69. fileName := part1.FileName()
  70. if fileName != "" {
  71. fileName = path.Base(fileName)
  72. }
  73. contentType := part1.Header.Get("Content-Type")
  74. if contentType == "application/octet-stream" {
  75. contentType = ""
  76. }
  77. if so.SaveInside {
  78. buf := bufPool.Get().(*bytes.Buffer)
  79. buf.Reset()
  80. buf.ReadFrom(part1)
  81. filerResult, replyerr = fs.saveMetaData(ctx, r, fileName, contentType, so, nil, nil, 0, buf.Bytes())
  82. bufPool.Put(buf)
  83. return
  84. }
  85. fileChunks, md5Hash, chunkOffset, err, smallContent := fs.uploadReaderToChunks(w, r, part1, chunkSize, fileName, contentType, contentLength, so)
  86. if err != nil {
  87. return nil, nil, err
  88. }
  89. md5bytes = md5Hash.Sum(nil)
  90. headerMd5 := r.Header.Get("Content-Md5")
  91. if headerMd5 != "" && !(util.Base64Encode(md5bytes) == headerMd5 || fmt.Sprintf("%x", md5bytes) == headerMd5) {
  92. fs.filer.DeleteChunks(fileChunks)
  93. return nil, nil, errors.New("The Content-Md5 you specified did not match what we received.")
  94. }
  95. filerResult, replyerr = fs.saveMetaData(ctx, r, fileName, contentType, so, md5bytes, fileChunks, chunkOffset, smallContent)
  96. if replyerr != nil {
  97. fs.filer.DeleteChunks(fileChunks)
  98. }
  99. return
  100. }
  101. 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) {
  102. fileName := path.Base(r.URL.Path)
  103. contentType := r.Header.Get("Content-Type")
  104. if contentType == "application/octet-stream" {
  105. contentType = ""
  106. }
  107. fileChunks, md5Hash, chunkOffset, err, smallContent := fs.uploadReaderToChunks(w, r, r.Body, chunkSize, fileName, contentType, contentLength, so)
  108. if err != nil {
  109. return nil, nil, err
  110. }
  111. md5bytes = md5Hash.Sum(nil)
  112. headerMd5 := r.Header.Get("Content-Md5")
  113. if headerMd5 != "" && !(util.Base64Encode(md5bytes) == headerMd5 || fmt.Sprintf("%x", md5bytes) == headerMd5) {
  114. fs.filer.DeleteChunks(fileChunks)
  115. return nil, nil, errors.New("The Content-Md5 you specified did not match what we received.")
  116. }
  117. filerResult, replyerr = fs.saveMetaData(ctx, r, fileName, contentType, so, md5bytes, fileChunks, chunkOffset, smallContent)
  118. if replyerr != nil {
  119. fs.filer.DeleteChunks(fileChunks)
  120. }
  121. return
  122. }
  123. func isAppend(r *http.Request) bool {
  124. return r.URL.Query().Get("op") == "append"
  125. }
  126. func skipCheckParentDirEntry(r *http.Request) bool {
  127. return r.URL.Query().Get("skipCheckParentDir") == "true"
  128. }
  129. 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) {
  130. // detect file mode
  131. modeStr := r.URL.Query().Get("mode")
  132. if modeStr == "" {
  133. modeStr = "0660"
  134. }
  135. mode, err := strconv.ParseUint(modeStr, 8, 32)
  136. if err != nil {
  137. glog.Errorf("Invalid mode format: %s, use 0660 by default", modeStr)
  138. mode = 0660
  139. }
  140. // fix the path
  141. path := r.URL.Path
  142. if strings.HasSuffix(path, "/") {
  143. if fileName != "" {
  144. path += fileName
  145. }
  146. } else {
  147. if fileName != "" {
  148. if possibleDirEntry, findDirErr := fs.filer.FindEntry(ctx, util.FullPath(path)); findDirErr == nil {
  149. if possibleDirEntry.IsDirectory() {
  150. path += "/" + fileName
  151. }
  152. }
  153. }
  154. }
  155. var entry *filer.Entry
  156. var newChunks []*filer_pb.FileChunk
  157. var mergedChunks []*filer_pb.FileChunk
  158. isAppend := isAppend(r)
  159. isOffsetWrite := len(fileChunks) > 0 && fileChunks[0].Offset > 0
  160. // when it is an append
  161. if isAppend || isOffsetWrite {
  162. existingEntry, findErr := fs.filer.FindEntry(ctx, util.FullPath(path))
  163. if findErr != nil && findErr != filer_pb.ErrNotFound {
  164. glog.V(0).Infof("failing to find %s: %v", path, findErr)
  165. }
  166. entry = existingEntry
  167. }
  168. if entry != nil {
  169. entry.Mtime = time.Now()
  170. entry.Md5 = nil
  171. // adjust chunk offsets
  172. if isAppend {
  173. for _, chunk := range fileChunks {
  174. chunk.Offset += int64(entry.FileSize)
  175. }
  176. entry.FileSize += uint64(chunkOffset)
  177. }
  178. newChunks = append(entry.GetChunks(), fileChunks...)
  179. // TODO
  180. if len(entry.Content) > 0 {
  181. replyerr = fmt.Errorf("append to small file is not supported yet")
  182. return
  183. }
  184. } else {
  185. glog.V(4).Infoln("saving", path)
  186. newChunks = fileChunks
  187. entry = &filer.Entry{
  188. FullPath: util.FullPath(path),
  189. Attr: filer.Attr{
  190. Mtime: time.Now(),
  191. Crtime: time.Now(),
  192. Mode: os.FileMode(mode),
  193. Uid: OS_UID,
  194. Gid: OS_GID,
  195. TtlSec: so.TtlSeconds,
  196. Mime: contentType,
  197. Md5: md5bytes,
  198. FileSize: uint64(chunkOffset),
  199. },
  200. Content: content,
  201. }
  202. }
  203. // maybe concatenate small chunks into one whole chunk
  204. mergedChunks, replyerr = fs.maybeMergeChunks(so, newChunks)
  205. if replyerr != nil {
  206. glog.V(0).Infof("merge chunks %s: %v", r.RequestURI, replyerr)
  207. mergedChunks = newChunks
  208. }
  209. // maybe compact entry chunks
  210. mergedChunks, replyerr = filer.MaybeManifestize(fs.saveAsChunk(so), mergedChunks)
  211. if replyerr != nil {
  212. glog.V(0).Infof("manifestize %s: %v", r.RequestURI, replyerr)
  213. return
  214. }
  215. entry.Chunks = mergedChunks
  216. if isOffsetWrite {
  217. entry.Md5 = nil
  218. entry.FileSize = entry.Size()
  219. }
  220. filerResult = &FilerPostResult{
  221. Name: fileName,
  222. Size: int64(entry.FileSize),
  223. }
  224. entry.Extended = SaveAmzMetaData(r, entry.Extended, false)
  225. for k, v := range r.Header {
  226. if len(v) > 0 && len(v[0]) > 0 {
  227. if strings.HasPrefix(k, needle.PairNamePrefix) || k == "Cache-Control" || k == "Expires" || k == "Content-Disposition" {
  228. entry.Extended[k] = []byte(v[0])
  229. }
  230. if k == "Response-Content-Disposition" {
  231. entry.Extended["Content-Disposition"] = []byte(v[0])
  232. }
  233. }
  234. }
  235. dbErr := fs.filer.CreateEntry(ctx, entry, false, false, nil, skipCheckParentDirEntry(r), so.MaxFileNameLength)
  236. // In test_bucket_listv2_delimiter_basic, the valid object key is the parent folder
  237. if dbErr != nil && strings.HasSuffix(dbErr.Error(), " is a file") && r.Header.Get(s3_constants.AmzIdentityId) != "" {
  238. dbErr = fs.filer.CreateEntry(ctx, entry, false, false, nil, true, so.MaxFileNameLength)
  239. }
  240. if dbErr != nil {
  241. replyerr = dbErr
  242. filerResult.Error = dbErr.Error()
  243. glog.V(0).Infof("failing to write %s to filer server : %v", path, dbErr)
  244. }
  245. return filerResult, replyerr
  246. }
  247. func (fs *FilerServer) saveAsChunk(so *operation.StorageOption) filer.SaveDataAsChunkFunctionType {
  248. return func(reader io.Reader, name string, offset int64, tsNs int64) (*filer_pb.FileChunk, error) {
  249. var fileId string
  250. var uploadResult *operation.UploadResult
  251. err := util.Retry("saveAsChunk", func() error {
  252. // assign one file id for one chunk
  253. assignedFileId, urlLocation, auth, assignErr := fs.assignNewFileInfo(so)
  254. if assignErr != nil {
  255. return assignErr
  256. }
  257. fileId = assignedFileId
  258. // upload the chunk to the volume server
  259. uploadOption := &operation.UploadOption{
  260. UploadUrl: urlLocation,
  261. Filename: name,
  262. Cipher: fs.option.Cipher,
  263. IsInputCompressed: false,
  264. MimeType: "",
  265. PairMap: nil,
  266. Jwt: auth,
  267. }
  268. var uploadErr error
  269. uploadResult, uploadErr, _ = operation.Upload(reader, uploadOption)
  270. if uploadErr != nil {
  271. return uploadErr
  272. }
  273. return nil
  274. })
  275. if err != nil {
  276. return nil, err
  277. }
  278. return uploadResult.ToPbFileChunk(fileId, offset, tsNs), nil
  279. }
  280. }
  281. func (fs *FilerServer) mkdir(ctx context.Context, w http.ResponseWriter, r *http.Request, so *operation.StorageOption) (filerResult *FilerPostResult, replyerr error) {
  282. // detect file mode
  283. modeStr := r.URL.Query().Get("mode")
  284. if modeStr == "" {
  285. modeStr = "0660"
  286. }
  287. mode, err := strconv.ParseUint(modeStr, 8, 32)
  288. if err != nil {
  289. glog.Errorf("Invalid mode format: %s, use 0660 by default", modeStr)
  290. mode = 0660
  291. }
  292. // fix the path
  293. path := r.URL.Path
  294. if strings.HasSuffix(path, "/") {
  295. path = path[:len(path)-1]
  296. }
  297. existingEntry, err := fs.filer.FindEntry(ctx, util.FullPath(path))
  298. if err == nil && existingEntry != nil {
  299. replyerr = fmt.Errorf("dir %s already exists", path)
  300. return
  301. }
  302. glog.V(4).Infoln("mkdir", path)
  303. entry := &filer.Entry{
  304. FullPath: util.FullPath(path),
  305. Attr: filer.Attr{
  306. Mtime: time.Now(),
  307. Crtime: time.Now(),
  308. Mode: os.FileMode(mode) | os.ModeDir,
  309. Uid: OS_UID,
  310. Gid: OS_GID,
  311. TtlSec: so.TtlSeconds,
  312. },
  313. }
  314. filerResult = &FilerPostResult{
  315. Name: util.FullPath(path).Name(),
  316. }
  317. if dbErr := fs.filer.CreateEntry(ctx, entry, false, false, nil, false, so.MaxFileNameLength); dbErr != nil {
  318. replyerr = dbErr
  319. filerResult.Error = dbErr.Error()
  320. glog.V(0).Infof("failing to create dir %s on filer server : %v", path, dbErr)
  321. }
  322. return filerResult, replyerr
  323. }
  324. func SaveAmzMetaData(r *http.Request, existing map[string][]byte, isReplace bool) (metadata map[string][]byte) {
  325. metadata = make(map[string][]byte)
  326. if !isReplace {
  327. for k, v := range existing {
  328. metadata[k] = v
  329. }
  330. }
  331. if sc := r.Header.Get(s3_constants.AmzStorageClass); sc != "" {
  332. metadata[s3_constants.AmzStorageClass] = []byte(sc)
  333. }
  334. if ce := r.Header.Get("Content-Encoding"); ce != "" {
  335. metadata["Content-Encoding"] = []byte(ce)
  336. }
  337. if tags := r.Header.Get(s3_constants.AmzObjectTagging); tags != "" {
  338. for _, v := range strings.Split(tags, "&") {
  339. tag := strings.Split(v, "=")
  340. if len(tag) == 2 {
  341. metadata[s3_constants.AmzObjectTagging+"-"+tag[0]] = []byte(tag[1])
  342. } else if len(tag) == 1 {
  343. metadata[s3_constants.AmzObjectTagging+"-"+tag[0]] = nil
  344. }
  345. }
  346. }
  347. for header, values := range r.Header {
  348. if strings.HasPrefix(header, s3_constants.AmzUserMetaPrefix) {
  349. for _, value := range values {
  350. metadata[header] = []byte(value)
  351. }
  352. }
  353. }
  354. //acp-owner
  355. acpOwner := r.Header.Get(s3_constants.ExtAmzOwnerKey)
  356. if len(acpOwner) > 0 {
  357. metadata[s3_constants.ExtAmzOwnerKey] = []byte(acpOwner)
  358. }
  359. //acp-grants
  360. acpGrants := r.Header.Get(s3_constants.ExtAmzAclKey)
  361. if len(acpOwner) > 0 {
  362. metadata[s3_constants.ExtAmzAclKey] = []byte(acpGrants)
  363. }
  364. return
  365. }