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.

365 lines
10 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
3 years ago
3 years ago
3 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. 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. isAppend := isAppend(r)
  140. isOffsetWrite := len(fileChunks) > 0 && fileChunks[0].Offset > 0
  141. // when it is an append
  142. if isAppend || isOffsetWrite {
  143. existingEntry, findErr := fs.filer.FindEntry(ctx, util.FullPath(path))
  144. if findErr != nil && findErr != filer_pb.ErrNotFound {
  145. glog.V(0).Infof("failing to find %s: %v", path, findErr)
  146. }
  147. entry = existingEntry
  148. }
  149. if entry != nil {
  150. entry.Mtime = time.Now()
  151. entry.Md5 = nil
  152. // adjust chunk offsets
  153. if isAppend {
  154. for _, chunk := range fileChunks {
  155. chunk.Offset += int64(entry.FileSize)
  156. }
  157. entry.FileSize += uint64(chunkOffset)
  158. }
  159. mergedChunks = append(entry.Chunks, fileChunks...)
  160. // TODO
  161. if len(entry.Content) > 0 {
  162. replyerr = fmt.Errorf("append to small file is not supported yet")
  163. return
  164. }
  165. } else {
  166. glog.V(4).Infoln("saving", path)
  167. mergedChunks = fileChunks
  168. entry = &filer.Entry{
  169. FullPath: util.FullPath(path),
  170. Attr: filer.Attr{
  171. Mtime: time.Now(),
  172. Crtime: time.Now(),
  173. Mode: os.FileMode(mode),
  174. Uid: OS_UID,
  175. Gid: OS_GID,
  176. Replication: so.Replication,
  177. Collection: so.Collection,
  178. TtlSec: so.TtlSeconds,
  179. DiskType: so.DiskType,
  180. Mime: contentType,
  181. Md5: md5bytes,
  182. FileSize: uint64(chunkOffset),
  183. },
  184. Content: content,
  185. }
  186. }
  187. // maybe compact entry chunks
  188. mergedChunks, replyerr = filer.MaybeManifestize(fs.saveAsChunk(so), mergedChunks)
  189. if replyerr != nil {
  190. glog.V(0).Infof("manifestize %s: %v", r.RequestURI, replyerr)
  191. return
  192. }
  193. entry.Chunks = mergedChunks
  194. if isOffsetWrite {
  195. entry.Md5 = nil
  196. entry.FileSize = entry.Size()
  197. }
  198. filerResult = &FilerPostResult{
  199. Name: fileName,
  200. Size: int64(entry.FileSize),
  201. }
  202. entry.Extended = SaveAmzMetaData(r, entry.Extended, false)
  203. for k, v := range r.Header {
  204. if len(v) > 0 && len(v[0]) > 0 {
  205. if strings.HasPrefix(k, needle.PairNamePrefix) || k == "Cache-Control" || k == "Expires" || k == "Content-Disposition" {
  206. entry.Extended[k] = []byte(v[0])
  207. }
  208. if k == "Response-Content-Disposition" {
  209. entry.Extended["Content-Disposition"] = []byte(v[0])
  210. }
  211. }
  212. }
  213. if dbErr := fs.filer.CreateEntry(ctx, entry, false, false, nil); dbErr != nil {
  214. replyerr = dbErr
  215. filerResult.Error = dbErr.Error()
  216. glog.V(0).Infof("failing to write %s to filer server : %v", path, dbErr)
  217. }
  218. return filerResult, replyerr
  219. }
  220. func (fs *FilerServer) saveAsChunk(so *operation.StorageOption) filer.SaveDataAsChunkFunctionType {
  221. return func(reader io.Reader, name string, offset int64) (*filer_pb.FileChunk, string, string, error) {
  222. // assign one file id for one chunk
  223. fileId, urlLocation, auth, assignErr := fs.assignNewFileInfo(so)
  224. if assignErr != nil {
  225. return nil, "", "", assignErr
  226. }
  227. // upload the chunk to the volume server
  228. uploadOption := &operation.UploadOption{
  229. UploadUrl: urlLocation,
  230. Filename: name,
  231. Cipher: fs.option.Cipher,
  232. IsInputCompressed: false,
  233. MimeType: "",
  234. PairMap: nil,
  235. Jwt: auth,
  236. }
  237. uploadResult, uploadErr, _ := operation.Upload(reader, uploadOption)
  238. if uploadErr != nil {
  239. return nil, "", "", uploadErr
  240. }
  241. return uploadResult.ToPbFileChunk(fileId, offset), so.Collection, so.Replication, nil
  242. }
  243. }
  244. func (fs *FilerServer) mkdir(ctx context.Context, w http.ResponseWriter, r *http.Request) (filerResult *FilerPostResult, replyerr error) {
  245. // detect file mode
  246. modeStr := r.URL.Query().Get("mode")
  247. if modeStr == "" {
  248. modeStr = "0660"
  249. }
  250. mode, err := strconv.ParseUint(modeStr, 8, 32)
  251. if err != nil {
  252. glog.Errorf("Invalid mode format: %s, use 0660 by default", modeStr)
  253. mode = 0660
  254. }
  255. // fix the path
  256. path := r.URL.Path
  257. if strings.HasSuffix(path, "/") {
  258. path = path[:len(path)-1]
  259. }
  260. existingEntry, err := fs.filer.FindEntry(ctx, util.FullPath(path))
  261. if err == nil && existingEntry != nil {
  262. replyerr = fmt.Errorf("dir %s already exists", path)
  263. return
  264. }
  265. glog.V(4).Infoln("mkdir", path)
  266. entry := &filer.Entry{
  267. FullPath: util.FullPath(path),
  268. Attr: filer.Attr{
  269. Mtime: time.Now(),
  270. Crtime: time.Now(),
  271. Mode: os.FileMode(mode) | os.ModeDir,
  272. Uid: OS_UID,
  273. Gid: OS_GID,
  274. },
  275. }
  276. filerResult = &FilerPostResult{
  277. Name: util.FullPath(path).Name(),
  278. }
  279. if dbErr := fs.filer.CreateEntry(ctx, entry, false, false, nil); dbErr != nil {
  280. replyerr = dbErr
  281. filerResult.Error = dbErr.Error()
  282. glog.V(0).Infof("failing to create dir %s on filer server : %v", path, dbErr)
  283. }
  284. return filerResult, replyerr
  285. }
  286. func SaveAmzMetaData(r *http.Request, existing map[string][]byte, isReplace bool) (metadata map[string][]byte) {
  287. metadata = make(map[string][]byte)
  288. if !isReplace {
  289. for k, v := range existing {
  290. metadata[k] = v
  291. }
  292. }
  293. if sc := r.Header.Get(xhttp.AmzStorageClass); sc != "" {
  294. metadata[xhttp.AmzStorageClass] = []byte(sc)
  295. }
  296. if tags := r.Header.Get(xhttp.AmzObjectTagging); tags != "" {
  297. for _, v := range strings.Split(tags, "&") {
  298. tag := strings.Split(v, "=")
  299. if len(tag) == 2 {
  300. metadata[xhttp.AmzObjectTagging+"-"+tag[0]] = []byte(tag[1])
  301. } else if len(tag) == 1 {
  302. metadata[xhttp.AmzObjectTagging+"-"+tag[0]] = nil
  303. }
  304. }
  305. }
  306. for header, values := range r.Header {
  307. if strings.HasPrefix(header, xhttp.AmzUserMetaPrefix) {
  308. for _, value := range values {
  309. metadata[header] = []byte(value)
  310. }
  311. }
  312. }
  313. return
  314. }