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.

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