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.

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