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.

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