filer_server_handlers_write_autochunk.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  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. }