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.

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