filer_server_handlers_write_autochunk.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  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 == http.MethodPost {
  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.DeleteUncommittedChunks(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.DeleteUncommittedChunks(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.DeleteUncommittedChunks(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.DeleteUncommittedChunks(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 isS3Request(r *http.Request) bool {
  130. return r.Header.Get(s3_constants.AmzAuthType) != "" || r.Header.Get("X-Amz-Date") != ""
  131. }
  132. 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) {
  133. // detect file mode
  134. modeStr := r.URL.Query().Get("mode")
  135. if modeStr == "" {
  136. modeStr = "0660"
  137. }
  138. mode, err := strconv.ParseUint(modeStr, 8, 32)
  139. if err != nil {
  140. glog.Errorf("Invalid mode format: %s, use 0660 by default", modeStr)
  141. mode = 0660
  142. }
  143. // fix the path
  144. path := r.URL.Path
  145. if strings.HasSuffix(path, "/") {
  146. if fileName != "" {
  147. path += fileName
  148. }
  149. } else {
  150. if fileName != "" {
  151. if possibleDirEntry, findDirErr := fs.filer.FindEntry(ctx, util.FullPath(path)); findDirErr == nil {
  152. if possibleDirEntry.IsDirectory() {
  153. path += "/" + fileName
  154. }
  155. }
  156. }
  157. }
  158. var entry *filer.Entry
  159. var newChunks []*filer_pb.FileChunk
  160. var mergedChunks []*filer_pb.FileChunk
  161. isAppend := isAppend(r)
  162. isOffsetWrite := len(fileChunks) > 0 && fileChunks[0].Offset > 0
  163. // when it is an append
  164. if isAppend || isOffsetWrite {
  165. existingEntry, findErr := fs.filer.FindEntry(ctx, util.FullPath(path))
  166. if findErr != nil && findErr != filer_pb.ErrNotFound {
  167. glog.V(0).Infof("failing to find %s: %v", path, findErr)
  168. }
  169. entry = existingEntry
  170. }
  171. if entry != nil {
  172. entry.Mtime = time.Now()
  173. entry.Md5 = nil
  174. // adjust chunk offsets
  175. if isAppend {
  176. for _, chunk := range fileChunks {
  177. chunk.Offset += int64(entry.FileSize)
  178. }
  179. entry.FileSize += uint64(chunkOffset)
  180. }
  181. newChunks = append(entry.GetChunks(), fileChunks...)
  182. // TODO
  183. if len(entry.Content) > 0 {
  184. replyerr = fmt.Errorf("append to small file is not supported yet")
  185. return
  186. }
  187. } else {
  188. glog.V(4).Infoln("saving", path)
  189. newChunks = fileChunks
  190. entry = &filer.Entry{
  191. FullPath: util.FullPath(path),
  192. Attr: filer.Attr{
  193. Mtime: time.Now(),
  194. Crtime: time.Now(),
  195. Mode: os.FileMode(mode),
  196. Uid: OS_UID,
  197. Gid: OS_GID,
  198. TtlSec: so.TtlSeconds,
  199. Mime: contentType,
  200. Md5: md5bytes,
  201. FileSize: uint64(chunkOffset),
  202. },
  203. Content: content,
  204. }
  205. }
  206. // maybe concatenate small chunks into one whole chunk
  207. mergedChunks, replyerr = fs.maybeMergeChunks(so, newChunks)
  208. if replyerr != nil {
  209. glog.V(0).Infof("merge chunks %s: %v", r.RequestURI, replyerr)
  210. mergedChunks = newChunks
  211. }
  212. // maybe compact entry chunks
  213. mergedChunks, replyerr = filer.MaybeManifestize(fs.saveAsChunk(so), mergedChunks)
  214. if replyerr != nil {
  215. glog.V(0).Infof("manifestize %s: %v", r.RequestURI, replyerr)
  216. return
  217. }
  218. entry.Chunks = mergedChunks
  219. if isOffsetWrite {
  220. entry.Md5 = nil
  221. entry.FileSize = entry.Size()
  222. }
  223. filerResult = &FilerPostResult{
  224. Name: fileName,
  225. Size: int64(entry.FileSize),
  226. }
  227. entry.Extended = SaveAmzMetaData(r, entry.Extended, false)
  228. for k, v := range r.Header {
  229. if len(v) > 0 && len(v[0]) > 0 {
  230. if strings.HasPrefix(k, needle.PairNamePrefix) || k == "Cache-Control" || k == "Expires" || k == "Content-Disposition" {
  231. entry.Extended[k] = []byte(v[0])
  232. }
  233. if k == "Response-Content-Disposition" {
  234. entry.Extended["Content-Disposition"] = []byte(v[0])
  235. }
  236. }
  237. }
  238. dbErr := fs.filer.CreateEntry(ctx, entry, false, false, nil, skipCheckParentDirEntry(r), so.MaxFileNameLength)
  239. // In test_bucket_listv2_delimiter_basic, the valid object key is the parent folder
  240. if dbErr != nil && strings.HasSuffix(dbErr.Error(), " is a file") && isS3Request(r) {
  241. dbErr = fs.filer.CreateEntry(ctx, entry, false, false, nil, true, so.MaxFileNameLength)
  242. }
  243. if dbErr != nil {
  244. replyerr = dbErr
  245. filerResult.Error = dbErr.Error()
  246. glog.V(0).Infof("failing to write %s to filer server : %v", path, dbErr)
  247. }
  248. return filerResult, replyerr
  249. }
  250. func (fs *FilerServer) saveAsChunk(so *operation.StorageOption) filer.SaveDataAsChunkFunctionType {
  251. return func(reader io.Reader, name string, offset int64, tsNs int64) (*filer_pb.FileChunk, error) {
  252. var fileId string
  253. var uploadResult *operation.UploadResult
  254. err := util.Retry("saveAsChunk", func() error {
  255. // assign one file id for one chunk
  256. assignedFileId, urlLocation, auth, assignErr := fs.assignNewFileInfo(so)
  257. if assignErr != nil {
  258. return assignErr
  259. }
  260. fileId = assignedFileId
  261. // upload the chunk to the volume server
  262. uploadOption := &operation.UploadOption{
  263. UploadUrl: urlLocation,
  264. Filename: name,
  265. Cipher: fs.option.Cipher,
  266. IsInputCompressed: false,
  267. MimeType: "",
  268. PairMap: nil,
  269. Jwt: auth,
  270. }
  271. uploader, uploaderErr := operation.NewUploader()
  272. if uploaderErr != nil {
  273. return uploaderErr
  274. }
  275. var uploadErr error
  276. uploadResult, uploadErr, _ = uploader.Upload(reader, uploadOption)
  277. if uploadErr != nil {
  278. return uploadErr
  279. }
  280. return nil
  281. })
  282. if err != nil {
  283. return nil, err
  284. }
  285. return uploadResult.ToPbFileChunk(fileId, offset, tsNs), nil
  286. }
  287. }
  288. func (fs *FilerServer) mkdir(ctx context.Context, w http.ResponseWriter, r *http.Request, so *operation.StorageOption) (filerResult *FilerPostResult, replyerr error) {
  289. // detect file mode
  290. modeStr := r.URL.Query().Get("mode")
  291. if modeStr == "" {
  292. modeStr = "0660"
  293. }
  294. mode, err := strconv.ParseUint(modeStr, 8, 32)
  295. if err != nil {
  296. glog.Errorf("Invalid mode format: %s, use 0660 by default", modeStr)
  297. mode = 0660
  298. }
  299. // fix the path
  300. path := r.URL.Path
  301. if strings.HasSuffix(path, "/") {
  302. path = path[:len(path)-1]
  303. }
  304. existingEntry, err := fs.filer.FindEntry(ctx, util.FullPath(path))
  305. if err == nil && existingEntry != nil {
  306. replyerr = fmt.Errorf("dir %s already exists", path)
  307. return
  308. }
  309. glog.V(4).Infoln("mkdir", path)
  310. entry := &filer.Entry{
  311. FullPath: util.FullPath(path),
  312. Attr: filer.Attr{
  313. Mtime: time.Now(),
  314. Crtime: time.Now(),
  315. Mode: os.FileMode(mode) | os.ModeDir,
  316. Uid: OS_UID,
  317. Gid: OS_GID,
  318. TtlSec: so.TtlSeconds,
  319. },
  320. }
  321. filerResult = &FilerPostResult{
  322. Name: util.FullPath(path).Name(),
  323. }
  324. if dbErr := fs.filer.CreateEntry(ctx, entry, false, false, nil, false, so.MaxFileNameLength); dbErr != nil {
  325. replyerr = dbErr
  326. filerResult.Error = dbErr.Error()
  327. glog.V(0).Infof("failing to create dir %s on filer server : %v", path, dbErr)
  328. }
  329. return filerResult, replyerr
  330. }
  331. func SaveAmzMetaData(r *http.Request, existing map[string][]byte, isReplace bool) (metadata map[string][]byte) {
  332. metadata = make(map[string][]byte)
  333. if !isReplace {
  334. for k, v := range existing {
  335. metadata[k] = v
  336. }
  337. }
  338. if sc := r.Header.Get(s3_constants.AmzStorageClass); sc != "" {
  339. metadata[s3_constants.AmzStorageClass] = []byte(sc)
  340. }
  341. if ce := r.Header.Get("Content-Encoding"); ce != "" {
  342. metadata["Content-Encoding"] = []byte(ce)
  343. }
  344. if tags := r.Header.Get(s3_constants.AmzObjectTagging); tags != "" {
  345. for _, v := range strings.Split(tags, "&") {
  346. tag := strings.Split(v, "=")
  347. if len(tag) == 2 {
  348. metadata[s3_constants.AmzObjectTagging+"-"+tag[0]] = []byte(tag[1])
  349. } else if len(tag) == 1 {
  350. metadata[s3_constants.AmzObjectTagging+"-"+tag[0]] = nil
  351. }
  352. }
  353. }
  354. for header, values := range r.Header {
  355. if strings.HasPrefix(header, s3_constants.AmzUserMetaPrefix) {
  356. for _, value := range values {
  357. metadata[header] = []byte(value)
  358. }
  359. }
  360. }
  361. //acp-owner
  362. acpOwner := r.Header.Get(s3_constants.ExtAmzOwnerKey)
  363. if len(acpOwner) > 0 {
  364. metadata[s3_constants.ExtAmzOwnerKey] = []byte(acpOwner)
  365. }
  366. //acp-grants
  367. acpGrants := r.Header.Get(s3_constants.ExtAmzAclKey)
  368. if len(acpOwner) > 0 {
  369. metadata[s3_constants.ExtAmzAclKey] = []byte(acpGrants)
  370. }
  371. return
  372. }