filer_server_handlers_write_autochunk.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  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, 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 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, so *operation.StorageOption) (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. TtlSec: so.TtlSeconds,
  296. },
  297. }
  298. filerResult = &FilerPostResult{
  299. Name: util.FullPath(path).Name(),
  300. }
  301. if dbErr := fs.filer.CreateEntry(ctx, entry, false, false, nil, false); dbErr != nil {
  302. replyerr = dbErr
  303. filerResult.Error = dbErr.Error()
  304. glog.V(0).Infof("failing to create dir %s on filer server : %v", path, dbErr)
  305. }
  306. return filerResult, replyerr
  307. }
  308. func SaveAmzMetaData(r *http.Request, existing map[string][]byte, isReplace bool) (metadata map[string][]byte) {
  309. metadata = make(map[string][]byte)
  310. if !isReplace {
  311. for k, v := range existing {
  312. metadata[k] = v
  313. }
  314. }
  315. if sc := r.Header.Get(s3_constants.AmzStorageClass); sc != "" {
  316. metadata[s3_constants.AmzStorageClass] = []byte(sc)
  317. }
  318. if ce := r.Header.Get("Content-Encoding"); ce != "" {
  319. metadata["Content-Encoding"] = []byte(ce)
  320. }
  321. if tags := r.Header.Get(s3_constants.AmzObjectTagging); tags != "" {
  322. for _, v := range strings.Split(tags, "&") {
  323. tag := strings.Split(v, "=")
  324. if len(tag) == 2 {
  325. metadata[s3_constants.AmzObjectTagging+"-"+tag[0]] = []byte(tag[1])
  326. } else if len(tag) == 1 {
  327. metadata[s3_constants.AmzObjectTagging+"-"+tag[0]] = nil
  328. }
  329. }
  330. }
  331. for header, values := range r.Header {
  332. if strings.HasPrefix(header, s3_constants.AmzUserMetaPrefix) {
  333. for _, value := range values {
  334. metadata[header] = []byte(value)
  335. }
  336. }
  337. }
  338. //acp-owner
  339. acpOwner := r.Header.Get(s3_constants.ExtAmzOwnerKey)
  340. if len(acpOwner) > 0 {
  341. metadata[s3_constants.ExtAmzOwnerKey] = []byte(acpOwner)
  342. }
  343. //acp-grants
  344. acpGrants := r.Header.Get(s3_constants.ExtAmzAclKey)
  345. if len(acpOwner) > 0 {
  346. metadata[s3_constants.ExtAmzAclKey] = []byte(acpGrants)
  347. }
  348. return
  349. }