filer_server_handlers_write_autochunk.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  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.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 (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. if dbErr := fs.filer.CreateEntry(ctx, entry, false, false, nil, skipCheckParentDirEntry(r), so.MaxFileNameLength); dbErr != nil {
  236. replyerr = dbErr
  237. filerResult.Error = dbErr.Error()
  238. glog.V(0).Infof("failing to write %s to filer server : %v", path, dbErr)
  239. }
  240. return filerResult, replyerr
  241. }
  242. func (fs *FilerServer) saveAsChunk(so *operation.StorageOption) filer.SaveDataAsChunkFunctionType {
  243. return func(reader io.Reader, name string, offset int64, tsNs int64) (*filer_pb.FileChunk, error) {
  244. var fileId string
  245. var uploadResult *operation.UploadResult
  246. err := util.Retry("saveAsChunk", func() error {
  247. // assign one file id for one chunk
  248. assignedFileId, urlLocation, auth, assignErr := fs.assignNewFileInfo(so)
  249. if assignErr != nil {
  250. return assignErr
  251. }
  252. fileId = assignedFileId
  253. // upload the chunk to the volume server
  254. uploadOption := &operation.UploadOption{
  255. UploadUrl: urlLocation,
  256. Filename: name,
  257. Cipher: fs.option.Cipher,
  258. IsInputCompressed: false,
  259. MimeType: "",
  260. PairMap: nil,
  261. Jwt: auth,
  262. }
  263. var uploadErr error
  264. uploadResult, uploadErr, _ = operation.Upload(reader, uploadOption)
  265. if uploadErr != nil {
  266. return uploadErr
  267. }
  268. return nil
  269. })
  270. if err != nil {
  271. return nil, err
  272. }
  273. return uploadResult.ToPbFileChunk(fileId, offset, tsNs), nil
  274. }
  275. }
  276. func (fs *FilerServer) mkdir(ctx context.Context, w http.ResponseWriter, r *http.Request, so *operation.StorageOption) (filerResult *FilerPostResult, replyerr error) {
  277. // detect file mode
  278. modeStr := r.URL.Query().Get("mode")
  279. if modeStr == "" {
  280. modeStr = "0660"
  281. }
  282. mode, err := strconv.ParseUint(modeStr, 8, 32)
  283. if err != nil {
  284. glog.Errorf("Invalid mode format: %s, use 0660 by default", modeStr)
  285. mode = 0660
  286. }
  287. // fix the path
  288. path := r.URL.Path
  289. if strings.HasSuffix(path, "/") {
  290. path = path[:len(path)-1]
  291. }
  292. existingEntry, err := fs.filer.FindEntry(ctx, util.FullPath(path))
  293. if err == nil && existingEntry != nil {
  294. replyerr = fmt.Errorf("dir %s already exists", path)
  295. return
  296. }
  297. glog.V(4).Infoln("mkdir", path)
  298. entry := &filer.Entry{
  299. FullPath: util.FullPath(path),
  300. Attr: filer.Attr{
  301. Mtime: time.Now(),
  302. Crtime: time.Now(),
  303. Mode: os.FileMode(mode) | os.ModeDir,
  304. Uid: OS_UID,
  305. Gid: OS_GID,
  306. TtlSec: so.TtlSeconds,
  307. },
  308. }
  309. filerResult = &FilerPostResult{
  310. Name: util.FullPath(path).Name(),
  311. }
  312. if dbErr := fs.filer.CreateEntry(ctx, entry, false, false, nil, false, so.MaxFileNameLength); dbErr != nil {
  313. replyerr = dbErr
  314. filerResult.Error = dbErr.Error()
  315. glog.V(0).Infof("failing to create dir %s on filer server : %v", path, dbErr)
  316. }
  317. return filerResult, replyerr
  318. }
  319. func SaveAmzMetaData(r *http.Request, existing map[string][]byte, isReplace bool) (metadata map[string][]byte) {
  320. metadata = make(map[string][]byte)
  321. if !isReplace {
  322. for k, v := range existing {
  323. metadata[k] = v
  324. }
  325. }
  326. if sc := r.Header.Get(s3_constants.AmzStorageClass); sc != "" {
  327. metadata[s3_constants.AmzStorageClass] = []byte(sc)
  328. }
  329. if ce := r.Header.Get("Content-Encoding"); ce != "" {
  330. metadata["Content-Encoding"] = []byte(ce)
  331. }
  332. if tags := r.Header.Get(s3_constants.AmzObjectTagging); tags != "" {
  333. for _, v := range strings.Split(tags, "&") {
  334. tag := strings.Split(v, "=")
  335. if len(tag) == 2 {
  336. metadata[s3_constants.AmzObjectTagging+"-"+tag[0]] = []byte(tag[1])
  337. } else if len(tag) == 1 {
  338. metadata[s3_constants.AmzObjectTagging+"-"+tag[0]] = nil
  339. }
  340. }
  341. }
  342. for header, values := range r.Header {
  343. if strings.HasPrefix(header, s3_constants.AmzUserMetaPrefix) {
  344. for _, value := range values {
  345. metadata[header] = []byte(value)
  346. }
  347. }
  348. }
  349. //acp-owner
  350. acpOwner := r.Header.Get(s3_constants.ExtAmzOwnerKey)
  351. if len(acpOwner) > 0 {
  352. metadata[s3_constants.ExtAmzOwnerKey] = []byte(acpOwner)
  353. }
  354. //acp-grants
  355. acpGrants := r.Header.Get(s3_constants.ExtAmzAclKey)
  356. if len(acpOwner) > 0 {
  357. metadata[s3_constants.ExtAmzAclKey] = []byte(acpGrants)
  358. }
  359. return
  360. }