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.

250 lines
7.2 KiB

9 years ago
6 years ago
9 years ago
9 years ago
9 years ago
7 years ago
9 years ago
7 years ago
6 years ago
9 years ago
9 years ago
9 years ago
6 years ago
6 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
6 years ago
9 years ago
9 years ago
9 years ago
6 years ago
6 years ago
6 years ago
9 years ago
9 years ago
  1. package weed_server
  2. import (
  3. "context"
  4. "encoding/json"
  5. "errors"
  6. "io"
  7. "io/ioutil"
  8. "mime"
  9. "net/http"
  10. "net/url"
  11. "os"
  12. filenamePath "path"
  13. "strconv"
  14. "strings"
  15. "time"
  16. "github.com/chrislusf/seaweedfs/weed/filer2"
  17. "github.com/chrislusf/seaweedfs/weed/glog"
  18. "github.com/chrislusf/seaweedfs/weed/operation"
  19. "github.com/chrislusf/seaweedfs/weed/pb/filer_pb"
  20. "github.com/chrislusf/seaweedfs/weed/security"
  21. "github.com/chrislusf/seaweedfs/weed/stats"
  22. "github.com/chrislusf/seaweedfs/weed/util"
  23. )
  24. var (
  25. OS_UID = uint32(os.Getuid())
  26. OS_GID = uint32(os.Getgid())
  27. )
  28. type FilerPostResult struct {
  29. Name string `json:"name,omitempty"`
  30. Size uint32 `json:"size,omitempty"`
  31. Error string `json:"error,omitempty"`
  32. Fid string `json:"fid,omitempty"`
  33. Url string `json:"url,omitempty"`
  34. }
  35. func (fs *FilerServer) assignNewFileInfo(w http.ResponseWriter, r *http.Request, replication, collection string, dataCenter string) (fileId, urlLocation string, auth security.EncodedJwt, err error) {
  36. ar := &operation.VolumeAssignRequest{
  37. Count: 1,
  38. Replication: replication,
  39. Collection: collection,
  40. Ttl: r.URL.Query().Get("ttl"),
  41. DataCenter: dataCenter,
  42. }
  43. var altRequest *operation.VolumeAssignRequest
  44. if dataCenter != "" {
  45. altRequest = &operation.VolumeAssignRequest{
  46. Count: 1,
  47. Replication: replication,
  48. Collection: collection,
  49. Ttl: r.URL.Query().Get("ttl"),
  50. DataCenter: "",
  51. }
  52. }
  53. assignResult, ae := operation.Assign(fs.filer.GetMaster(), fs.grpcDialOption, ar, altRequest)
  54. if ae != nil {
  55. glog.Errorf("failing to assign a file id: %v", ae)
  56. writeJsonError(w, r, http.StatusInternalServerError, ae)
  57. err = ae
  58. return
  59. }
  60. fileId = assignResult.Fid
  61. urlLocation = "http://" + assignResult.Url + "/" + assignResult.Fid
  62. auth = assignResult.Auth
  63. return
  64. }
  65. func (fs *FilerServer) PostHandler(w http.ResponseWriter, r *http.Request) {
  66. stats.FilerRequestCounter.WithLabelValues("post").Inc()
  67. start := time.Now()
  68. defer func() { stats.FilerRequestHistogram.WithLabelValues("post").Observe(time.Since(start).Seconds()) }()
  69. ctx := context.Background()
  70. query := r.URL.Query()
  71. replication := query.Get("replication")
  72. if replication == "" {
  73. replication = fs.option.DefaultReplication
  74. }
  75. collection := query.Get("collection")
  76. if collection == "" {
  77. collection = fs.option.Collection
  78. }
  79. dataCenter := query.Get("dataCenter")
  80. if dataCenter == "" {
  81. dataCenter = fs.option.DataCenter
  82. }
  83. if autoChunked := fs.autoChunk(ctx, w, r, replication, collection, dataCenter); autoChunked {
  84. return
  85. }
  86. fileId, urlLocation, auth, err := fs.assignNewFileInfo(w, r, replication, collection, dataCenter)
  87. if err != nil || fileId == "" || urlLocation == "" {
  88. glog.V(0).Infof("fail to allocate volume for %s, collection:%s, datacenter:%s", r.URL.Path, collection, dataCenter)
  89. return
  90. }
  91. glog.V(4).Infof("write %s to %v", r.URL.Path, urlLocation)
  92. u, _ := url.Parse(urlLocation)
  93. // This allows a client to generate a chunk manifest and submit it to the filer -- it is a little off
  94. // because they need to provide FIDs instead of file paths...
  95. cm, _ := strconv.ParseBool(query.Get("cm"))
  96. if cm {
  97. q := u.Query()
  98. q.Set("cm", "true")
  99. u.RawQuery = q.Encode()
  100. }
  101. glog.V(4).Infoln("post to", u)
  102. // send request to volume server
  103. request := &http.Request{
  104. Method: r.Method,
  105. URL: u,
  106. Proto: r.Proto,
  107. ProtoMajor: r.ProtoMajor,
  108. ProtoMinor: r.ProtoMinor,
  109. Header: r.Header,
  110. Body: r.Body,
  111. Host: r.Host,
  112. ContentLength: r.ContentLength,
  113. }
  114. if auth != "" {
  115. request.Header.Set("Authorization", "BEARER "+string(auth))
  116. }
  117. resp, do_err := util.Do(request)
  118. if do_err != nil {
  119. glog.Errorf("failing to connect to volume server %s: %v, %+v", r.RequestURI, do_err, r.Method)
  120. writeJsonError(w, r, http.StatusInternalServerError, do_err)
  121. return
  122. }
  123. defer func() {
  124. io.Copy(ioutil.Discard, resp.Body)
  125. resp.Body.Close()
  126. }()
  127. etag := resp.Header.Get("ETag")
  128. resp_body, ra_err := ioutil.ReadAll(resp.Body)
  129. if ra_err != nil {
  130. glog.V(0).Infoln("failing to upload to volume server", r.RequestURI, ra_err.Error())
  131. writeJsonError(w, r, http.StatusInternalServerError, ra_err)
  132. return
  133. }
  134. glog.V(4).Infoln("post result", string(resp_body))
  135. var ret operation.UploadResult
  136. unmarshal_err := json.Unmarshal(resp_body, &ret)
  137. if unmarshal_err != nil {
  138. glog.V(0).Infoln("failing to read upload resonse", r.RequestURI, string(resp_body))
  139. writeJsonError(w, r, http.StatusInternalServerError, unmarshal_err)
  140. return
  141. }
  142. if ret.Error != "" {
  143. glog.V(0).Infoln("failing to post to volume server", r.RequestURI, ret.Error)
  144. writeJsonError(w, r, http.StatusInternalServerError, errors.New(ret.Error))
  145. return
  146. }
  147. // find correct final path
  148. path := r.URL.Path
  149. if strings.HasSuffix(path, "/") {
  150. if ret.Name != "" {
  151. path += ret.Name
  152. } else {
  153. fs.filer.DeleteFileByFileId(fileId)
  154. glog.V(0).Infoln("Can not to write to folder", path, "without a file name!")
  155. writeJsonError(w, r, http.StatusInternalServerError,
  156. errors.New("Can not to write to folder "+path+" without a file name"))
  157. return
  158. }
  159. }
  160. // update metadata in filer store
  161. existingEntry, err := fs.filer.FindEntry(ctx, filer2.FullPath(path))
  162. crTime := time.Now()
  163. if err == nil && existingEntry != nil {
  164. // glog.V(4).Infof("existing %s => %+v", path, existingEntry)
  165. if existingEntry.IsDirectory() {
  166. path += "/" + ret.Name
  167. } else {
  168. crTime = existingEntry.Crtime
  169. }
  170. }
  171. entry := &filer2.Entry{
  172. FullPath: filer2.FullPath(path),
  173. Attr: filer2.Attr{
  174. Mtime: time.Now(),
  175. Crtime: crTime,
  176. Mode: 0660,
  177. Uid: OS_UID,
  178. Gid: OS_GID,
  179. Replication: replication,
  180. Collection: collection,
  181. TtlSec: int32(util.ParseInt(r.URL.Query().Get("ttl"), 0)),
  182. },
  183. Chunks: []*filer_pb.FileChunk{{
  184. FileId: fileId,
  185. Size: uint64(ret.Size),
  186. Mtime: time.Now().UnixNano(),
  187. ETag: etag,
  188. }},
  189. }
  190. if ext := filenamePath.Ext(path); ext != "" {
  191. entry.Attr.Mime = mime.TypeByExtension(ext)
  192. }
  193. // glog.V(4).Infof("saving %s => %+v", path, entry)
  194. if db_err := fs.filer.CreateEntry(ctx, entry); db_err != nil {
  195. fs.filer.DeleteChunks(entry.FullPath, entry.Chunks)
  196. glog.V(0).Infof("failing to write %s to filer server : %v", path, db_err)
  197. writeJsonError(w, r, http.StatusInternalServerError, db_err)
  198. return
  199. }
  200. // send back post result
  201. reply := FilerPostResult{
  202. Name: ret.Name,
  203. Size: ret.Size,
  204. Error: ret.Error,
  205. Fid: fileId,
  206. Url: urlLocation,
  207. }
  208. setEtag(w, etag)
  209. writeJsonQuiet(w, r, http.StatusCreated, reply)
  210. }
  211. // curl -X DELETE http://localhost:8888/path/to
  212. // curl -X DELETE http://localhost:8888/path/to?recursive=true
  213. func (fs *FilerServer) DeleteHandler(w http.ResponseWriter, r *http.Request) {
  214. stats.FilerRequestCounter.WithLabelValues("delete").Inc()
  215. start := time.Now()
  216. defer func() { stats.FilerRequestHistogram.WithLabelValues("delete").Observe(time.Since(start).Seconds()) }()
  217. isRecursive := r.FormValue("recursive") == "true"
  218. err := fs.filer.DeleteEntryMetaAndData(context.Background(), filer2.FullPath(r.URL.Path), isRecursive, true)
  219. if err != nil {
  220. glog.V(1).Infoln("deleting", r.URL.Path, ":", err.Error())
  221. writeJsonError(w, r, http.StatusInternalServerError, err)
  222. return
  223. }
  224. w.WriteHeader(http.StatusNoContent)
  225. }