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.

338 lines
9.4 KiB

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