You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

344 lines
9.6 KiB

5 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
  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. return
  87. }
  88. 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) {
  89. fileName := path.Base(r.URL.Path)
  90. contentType := r.Header.Get("Content-Type")
  91. if contentType == "application/octet-stream" {
  92. contentType = ""
  93. }
  94. fileChunks, md5Hash, chunkOffset, err, smallContent := fs.uploadReaderToChunks(w, r, r.Body, chunkSize, fileName, contentType, contentLength, so)
  95. if err != nil {
  96. return nil, nil, err
  97. }
  98. md5bytes = md5Hash.Sum(nil)
  99. filerResult, replyerr = fs.saveMetaData(ctx, r, fileName, contentType, so, md5bytes, fileChunks, chunkOffset, smallContent)
  100. return
  101. }
  102. func isAppend(r *http.Request) bool {
  103. return r.URL.Query().Get("op") == "append"
  104. }
  105. 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) {
  106. // detect file mode
  107. modeStr := r.URL.Query().Get("mode")
  108. if modeStr == "" {
  109. modeStr = "0660"
  110. }
  111. mode, err := strconv.ParseUint(modeStr, 8, 32)
  112. if err != nil {
  113. glog.Errorf("Invalid mode format: %s, use 0660 by default", modeStr)
  114. mode = 0660
  115. }
  116. // fix the path
  117. path := r.URL.Path
  118. if strings.HasSuffix(path, "/") {
  119. if fileName != "" {
  120. path += fileName
  121. }
  122. } else {
  123. if fileName != "" {
  124. if possibleDirEntry, findDirErr := fs.filer.FindEntry(ctx, util.FullPath(path)); findDirErr == nil {
  125. if possibleDirEntry.IsDirectory() {
  126. path += "/" + fileName
  127. }
  128. }
  129. }
  130. }
  131. var entry *filer.Entry
  132. var mergedChunks []*filer_pb.FileChunk
  133. // when it is an append
  134. if isAppend(r) {
  135. existingEntry, findErr := fs.filer.FindEntry(ctx, util.FullPath(path))
  136. if findErr != nil && findErr != filer_pb.ErrNotFound {
  137. glog.V(0).Infof("failing to find %s: %v", path, findErr)
  138. }
  139. entry = existingEntry
  140. }
  141. if entry != nil {
  142. entry.Mtime = time.Now()
  143. entry.Md5 = nil
  144. // adjust chunk offsets
  145. for _, chunk := range fileChunks {
  146. chunk.Offset += int64(entry.FileSize)
  147. }
  148. mergedChunks = append(entry.Chunks, fileChunks...)
  149. entry.FileSize += uint64(chunkOffset)
  150. // TODO
  151. if len(entry.Content) > 0 {
  152. replyerr = fmt.Errorf("append to small file is not supported yet")
  153. return
  154. }
  155. } else {
  156. glog.V(4).Infoln("saving", path)
  157. mergedChunks = fileChunks
  158. entry = &filer.Entry{
  159. FullPath: util.FullPath(path),
  160. Attr: filer.Attr{
  161. Mtime: time.Now(),
  162. Crtime: time.Now(),
  163. Mode: os.FileMode(mode),
  164. Uid: OS_UID,
  165. Gid: OS_GID,
  166. Replication: so.Replication,
  167. Collection: so.Collection,
  168. TtlSec: so.TtlSeconds,
  169. DiskType: so.DiskType,
  170. Mime: contentType,
  171. Md5: md5bytes,
  172. FileSize: uint64(chunkOffset),
  173. },
  174. Content: content,
  175. }
  176. }
  177. // maybe compact entry chunks
  178. mergedChunks, replyerr = filer.MaybeManifestize(fs.saveAsChunk(so), mergedChunks)
  179. if replyerr != nil {
  180. glog.V(0).Infof("manifestize %s: %v", r.RequestURI, replyerr)
  181. return
  182. }
  183. entry.Chunks = mergedChunks
  184. filerResult = &FilerPostResult{
  185. Name: fileName,
  186. Size: int64(entry.FileSize),
  187. }
  188. entry.Extended = SaveAmzMetaData(r, entry.Extended, false)
  189. for k, v := range r.Header {
  190. if len(v) > 0 && (strings.HasPrefix(k, needle.PairNamePrefix) || k == "Cache-Control" || k == "Expires") {
  191. entry.Extended[k] = []byte(v[0])
  192. }
  193. }
  194. if dbErr := fs.filer.CreateEntry(ctx, entry, false, false, nil); dbErr != nil {
  195. fs.filer.DeleteChunks(fileChunks)
  196. replyerr = dbErr
  197. filerResult.Error = dbErr.Error()
  198. glog.V(0).Infof("failing to write %s to filer server : %v", path, dbErr)
  199. }
  200. return filerResult, replyerr
  201. }
  202. func (fs *FilerServer) saveAsChunk(so *operation.StorageOption) filer.SaveDataAsChunkFunctionType {
  203. return func(reader io.Reader, name string, offset int64) (*filer_pb.FileChunk, string, string, error) {
  204. // assign one file id for one chunk
  205. fileId, urlLocation, auth, assignErr := fs.assignNewFileInfo(so)
  206. if assignErr != nil {
  207. return nil, "", "", assignErr
  208. }
  209. // upload the chunk to the volume server
  210. uploadOption := &operation.UploadOption{
  211. UploadUrl: urlLocation,
  212. Filename: name,
  213. Cipher: fs.option.Cipher,
  214. IsInputCompressed: false,
  215. MimeType: "",
  216. PairMap: nil,
  217. Jwt: auth,
  218. }
  219. uploadResult, uploadErr, _ := operation.Upload(reader, uploadOption)
  220. if uploadErr != nil {
  221. return nil, "", "", uploadErr
  222. }
  223. return uploadResult.ToPbFileChunk(fileId, offset), so.Collection, so.Replication, nil
  224. }
  225. }
  226. func (fs *FilerServer) mkdir(ctx context.Context, w http.ResponseWriter, r *http.Request) (filerResult *FilerPostResult, replyerr error) {
  227. // detect file mode
  228. modeStr := r.URL.Query().Get("mode")
  229. if modeStr == "" {
  230. modeStr = "0660"
  231. }
  232. mode, err := strconv.ParseUint(modeStr, 8, 32)
  233. if err != nil {
  234. glog.Errorf("Invalid mode format: %s, use 0660 by default", modeStr)
  235. mode = 0660
  236. }
  237. // fix the path
  238. path := r.URL.Path
  239. if strings.HasSuffix(path, "/") {
  240. path = path[:len(path)-1]
  241. }
  242. existingEntry, err := fs.filer.FindEntry(ctx, util.FullPath(path))
  243. if err == nil && existingEntry != nil {
  244. replyerr = fmt.Errorf("dir %s already exists", path)
  245. return
  246. }
  247. glog.V(4).Infoln("mkdir", path)
  248. entry := &filer.Entry{
  249. FullPath: util.FullPath(path),
  250. Attr: filer.Attr{
  251. Mtime: time.Now(),
  252. Crtime: time.Now(),
  253. Mode: os.FileMode(mode) | os.ModeDir,
  254. Uid: OS_UID,
  255. Gid: OS_GID,
  256. },
  257. }
  258. filerResult = &FilerPostResult{
  259. Name: util.FullPath(path).Name(),
  260. }
  261. if dbErr := fs.filer.CreateEntry(ctx, entry, false, false, nil); dbErr != nil {
  262. replyerr = dbErr
  263. filerResult.Error = dbErr.Error()
  264. glog.V(0).Infof("failing to create dir %s on filer server : %v", path, dbErr)
  265. }
  266. return filerResult, replyerr
  267. }
  268. func SaveAmzMetaData(r *http.Request, existing map[string][]byte, isReplace bool) (metadata map[string][]byte) {
  269. metadata = make(map[string][]byte)
  270. if !isReplace {
  271. for k, v := range existing {
  272. metadata[k] = v
  273. }
  274. }
  275. if sc := r.Header.Get(xhttp.AmzStorageClass); sc != "" {
  276. metadata[xhttp.AmzStorageClass] = []byte(sc)
  277. }
  278. if tags := r.Header.Get(xhttp.AmzObjectTagging); tags != "" {
  279. for _, v := range strings.Split(tags, "&") {
  280. tag := strings.Split(v, "=")
  281. if len(tag) == 2 {
  282. metadata[xhttp.AmzObjectTagging+"-"+tag[0]] = []byte(tag[1])
  283. }
  284. }
  285. }
  286. for header, values := range r.Header {
  287. if strings.HasPrefix(header, xhttp.AmzUserMetaPrefix) {
  288. for _, value := range values {
  289. metadata[header] = []byte(value)
  290. }
  291. }
  292. }
  293. return
  294. }