filer_server_handlers_write_autochunk.go 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  1. package weed_server
  2. import (
  3. "context"
  4. "fmt"
  5. "io"
  6. "net/http"
  7. "os"
  8. "path"
  9. "strconv"
  10. "strings"
  11. "time"
  12. "github.com/chrislusf/seaweedfs/weed/filer"
  13. "github.com/chrislusf/seaweedfs/weed/glog"
  14. "github.com/chrislusf/seaweedfs/weed/operation"
  15. "github.com/chrislusf/seaweedfs/weed/pb/filer_pb"
  16. xhttp "github.com/chrislusf/seaweedfs/weed/s3api/http"
  17. "github.com/chrislusf/seaweedfs/weed/stats"
  18. "github.com/chrislusf/seaweedfs/weed/storage/needle"
  19. "github.com/chrislusf/seaweedfs/weed/util"
  20. )
  21. func (fs *FilerServer) autoChunk(ctx context.Context, w http.ResponseWriter, r *http.Request, contentLength int64, so *operation.StorageOption) {
  22. // autoChunking can be set at the command-line level or as a query param. Query param overrides command-line
  23. query := r.URL.Query()
  24. parsedMaxMB, _ := strconv.ParseInt(query.Get("maxMB"), 10, 32)
  25. maxMB := int32(parsedMaxMB)
  26. if maxMB <= 0 && fs.option.MaxMB > 0 {
  27. maxMB = int32(fs.option.MaxMB)
  28. }
  29. chunkSize := 1024 * 1024 * maxMB
  30. stats.FilerRequestCounter.WithLabelValues("chunk").Inc()
  31. start := time.Now()
  32. defer func() {
  33. stats.FilerRequestHistogram.WithLabelValues("chunk").Observe(time.Since(start).Seconds())
  34. }()
  35. var reply *FilerPostResult
  36. var err error
  37. var md5bytes []byte
  38. if r.Method == "POST" {
  39. if r.Header.Get("Content-Type") == "" && strings.HasSuffix(r.URL.Path, "/") {
  40. reply, err = fs.mkdir(ctx, w, r)
  41. } else {
  42. reply, md5bytes, err = fs.doPostAutoChunk(ctx, w, r, chunkSize, contentLength, so)
  43. }
  44. } else {
  45. reply, md5bytes, err = fs.doPutAutoChunk(ctx, w, r, chunkSize, contentLength, so)
  46. }
  47. if err != nil {
  48. if strings.HasPrefix(err.Error(), "read input:") {
  49. writeJsonError(w, r, 499, err)
  50. } else if strings.HasSuffix(err.Error(), "is a file") {
  51. writeJsonError(w, r, http.StatusConflict, err)
  52. } else {
  53. writeJsonError(w, r, http.StatusInternalServerError, err)
  54. }
  55. } else if reply != nil {
  56. if len(md5bytes) > 0 {
  57. md5InBase64 := util.Base64Encode(md5bytes)
  58. w.Header().Set("Content-MD5", md5InBase64)
  59. }
  60. writeJsonQuiet(w, r, http.StatusCreated, reply)
  61. }
  62. }
  63. 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) {
  64. multipartReader, multipartReaderErr := r.MultipartReader()
  65. if multipartReaderErr != nil {
  66. return nil, nil, multipartReaderErr
  67. }
  68. part1, part1Err := multipartReader.NextPart()
  69. if part1Err != nil {
  70. return nil, nil, part1Err
  71. }
  72. fileName := part1.FileName()
  73. if fileName != "" {
  74. fileName = path.Base(fileName)
  75. }
  76. contentType := part1.Header.Get("Content-Type")
  77. if contentType == "application/octet-stream" {
  78. contentType = ""
  79. }
  80. fileChunks, md5Hash, chunkOffset, err, smallContent := fs.uploadReaderToChunks(w, r, part1, chunkSize, fileName, contentType, contentLength, so)
  81. if err != nil {
  82. return nil, nil, err
  83. }
  84. md5bytes = md5Hash.Sum(nil)
  85. filerResult, replyerr = fs.saveMetaData(ctx, r, fileName, contentType, so, md5bytes, fileChunks, chunkOffset, smallContent)
  86. if replyerr != nil {
  87. fs.filer.DeleteChunks(fileChunks)
  88. }
  89. return
  90. }
  91. 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) {
  92. fileName := path.Base(r.URL.Path)
  93. contentType := r.Header.Get("Content-Type")
  94. if contentType == "application/octet-stream" {
  95. contentType = ""
  96. }
  97. fileChunks, md5Hash, chunkOffset, err, smallContent := fs.uploadReaderToChunks(w, r, r.Body, chunkSize, fileName, contentType, contentLength, so)
  98. if err != nil {
  99. return nil, nil, err
  100. }
  101. md5bytes = md5Hash.Sum(nil)
  102. filerResult, replyerr = fs.saveMetaData(ctx, r, fileName, contentType, so, md5bytes, fileChunks, chunkOffset, smallContent)
  103. if replyerr != nil {
  104. fs.filer.DeleteChunks(fileChunks)
  105. }
  106. return
  107. }
  108. func isAppend(r *http.Request) bool {
  109. return r.URL.Query().Get("op") == "append"
  110. }
  111. 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) {
  112. // detect file mode
  113. modeStr := r.URL.Query().Get("mode")
  114. if modeStr == "" {
  115. modeStr = "0660"
  116. }
  117. mode, err := strconv.ParseUint(modeStr, 8, 32)
  118. if err != nil {
  119. glog.Errorf("Invalid mode format: %s, use 0660 by default", modeStr)
  120. mode = 0660
  121. }
  122. // fix the path
  123. path := r.URL.Path
  124. if strings.HasSuffix(path, "/") {
  125. if fileName != "" {
  126. path += fileName
  127. }
  128. } else {
  129. if fileName != "" {
  130. if possibleDirEntry, findDirErr := fs.filer.FindEntry(ctx, util.FullPath(path)); findDirErr == nil {
  131. if possibleDirEntry.IsDirectory() {
  132. path += "/" + fileName
  133. }
  134. }
  135. }
  136. }
  137. var entry *filer.Entry
  138. var mergedChunks []*filer_pb.FileChunk
  139. // when it is an append
  140. if isAppend(r) {
  141. existingEntry, findErr := fs.filer.FindEntry(ctx, util.FullPath(path))
  142. if findErr != nil && findErr != filer_pb.ErrNotFound {
  143. glog.V(0).Infof("failing to find %s: %v", path, findErr)
  144. }
  145. entry = existingEntry
  146. }
  147. if entry != nil {
  148. entry.Mtime = time.Now()
  149. entry.Md5 = nil
  150. // adjust chunk offsets
  151. for _, chunk := range fileChunks {
  152. chunk.Offset += int64(entry.FileSize)
  153. }
  154. mergedChunks = append(entry.Chunks, fileChunks...)
  155. entry.FileSize += uint64(chunkOffset)
  156. // TODO
  157. if len(entry.Content) > 0 {
  158. replyerr = fmt.Errorf("append to small file is not supported yet")
  159. return
  160. }
  161. } else {
  162. glog.V(4).Infoln("saving", path)
  163. mergedChunks = fileChunks
  164. entry = &filer.Entry{
  165. FullPath: util.FullPath(path),
  166. Attr: filer.Attr{
  167. Mtime: time.Now(),
  168. Crtime: time.Now(),
  169. Mode: os.FileMode(mode),
  170. Uid: OS_UID,
  171. Gid: OS_GID,
  172. Replication: so.Replication,
  173. Collection: so.Collection,
  174. TtlSec: so.TtlSeconds,
  175. DiskType: so.DiskType,
  176. Mime: contentType,
  177. Md5: md5bytes,
  178. FileSize: uint64(chunkOffset),
  179. },
  180. Content: content,
  181. }
  182. }
  183. // maybe compact entry chunks
  184. mergedChunks, replyerr = filer.MaybeManifestize(fs.saveAsChunk(so), mergedChunks)
  185. if replyerr != nil {
  186. glog.V(0).Infof("manifestize %s: %v", r.RequestURI, replyerr)
  187. return
  188. }
  189. entry.Chunks = mergedChunks
  190. filerResult = &FilerPostResult{
  191. Name: fileName,
  192. Size: int64(entry.FileSize),
  193. }
  194. entry.Extended = SaveAmzMetaData(r, entry.Extended, false)
  195. for k, v := range r.Header {
  196. if len(v) > 0 && len(v[0]) > 0 {
  197. if strings.HasPrefix(k, needle.PairNamePrefix) || k == "Cache-Control" || k == "Expires" || k == "Content-Disposition" {
  198. entry.Extended[k] = []byte(v[0])
  199. }
  200. if k == "Response-Content-Disposition" {
  201. entry.Extended["Content-Disposition"] = []byte(v[0])
  202. }
  203. }
  204. }
  205. if dbErr := fs.filer.CreateEntry(ctx, entry, false, false, nil); dbErr != nil {
  206. replyerr = dbErr
  207. filerResult.Error = dbErr.Error()
  208. glog.V(0).Infof("failing to write %s to filer server : %v", path, dbErr)
  209. }
  210. return filerResult, replyerr
  211. }
  212. func (fs *FilerServer) saveAsChunk(so *operation.StorageOption) filer.SaveDataAsChunkFunctionType {
  213. return func(reader io.Reader, name string, offset int64) (*filer_pb.FileChunk, string, string, error) {
  214. // assign one file id for one chunk
  215. fileId, urlLocation, auth, assignErr := fs.assignNewFileInfo(so)
  216. if assignErr != nil {
  217. return nil, "", "", assignErr
  218. }
  219. // upload the chunk to the volume server
  220. uploadOption := &operation.UploadOption{
  221. UploadUrl: urlLocation,
  222. Filename: name,
  223. Cipher: fs.option.Cipher,
  224. IsInputCompressed: false,
  225. MimeType: "",
  226. PairMap: nil,
  227. Jwt: auth,
  228. }
  229. uploadResult, uploadErr, _ := operation.Upload(reader, uploadOption)
  230. if uploadErr != nil {
  231. return nil, "", "", uploadErr
  232. }
  233. return uploadResult.ToPbFileChunk(fileId, offset), so.Collection, so.Replication, nil
  234. }
  235. }
  236. func (fs *FilerServer) mkdir(ctx context.Context, w http.ResponseWriter, r *http.Request) (filerResult *FilerPostResult, replyerr error) {
  237. // detect file mode
  238. modeStr := r.URL.Query().Get("mode")
  239. if modeStr == "" {
  240. modeStr = "0660"
  241. }
  242. mode, err := strconv.ParseUint(modeStr, 8, 32)
  243. if err != nil {
  244. glog.Errorf("Invalid mode format: %s, use 0660 by default", modeStr)
  245. mode = 0660
  246. }
  247. // fix the path
  248. path := r.URL.Path
  249. if strings.HasSuffix(path, "/") {
  250. path = path[:len(path)-1]
  251. }
  252. existingEntry, err := fs.filer.FindEntry(ctx, util.FullPath(path))
  253. if err == nil && existingEntry != nil {
  254. replyerr = fmt.Errorf("dir %s already exists", path)
  255. return
  256. }
  257. glog.V(4).Infoln("mkdir", path)
  258. entry := &filer.Entry{
  259. FullPath: util.FullPath(path),
  260. Attr: filer.Attr{
  261. Mtime: time.Now(),
  262. Crtime: time.Now(),
  263. Mode: os.FileMode(mode) | os.ModeDir,
  264. Uid: OS_UID,
  265. Gid: OS_GID,
  266. },
  267. }
  268. filerResult = &FilerPostResult{
  269. Name: util.FullPath(path).Name(),
  270. }
  271. if dbErr := fs.filer.CreateEntry(ctx, entry, false, false, nil); dbErr != nil {
  272. replyerr = dbErr
  273. filerResult.Error = dbErr.Error()
  274. glog.V(0).Infof("failing to create dir %s on filer server : %v", path, dbErr)
  275. }
  276. return filerResult, replyerr
  277. }
  278. func SaveAmzMetaData(r *http.Request, existing map[string][]byte, isReplace bool) (metadata map[string][]byte) {
  279. metadata = make(map[string][]byte)
  280. if !isReplace {
  281. for k, v := range existing {
  282. metadata[k] = v
  283. }
  284. }
  285. if sc := r.Header.Get(xhttp.AmzStorageClass); sc != "" {
  286. metadata[xhttp.AmzStorageClass] = []byte(sc)
  287. }
  288. if tags := r.Header.Get(xhttp.AmzObjectTagging); tags != "" {
  289. for _, v := range strings.Split(tags, "&") {
  290. tag := strings.Split(v, "=")
  291. if len(tag) == 2 {
  292. metadata[xhttp.AmzObjectTagging+"-"+tag[0]] = []byte(tag[1])
  293. } else if len(tag) == 1 {
  294. metadata[xhttp.AmzObjectTagging+"-"+tag[0]] = nil
  295. }
  296. }
  297. }
  298. for header, values := range r.Header {
  299. if strings.HasPrefix(header, xhttp.AmzUserMetaPrefix) {
  300. for _, value := range values {
  301. metadata[header] = []byte(value)
  302. }
  303. }
  304. }
  305. return
  306. }