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.

242 lines
7.2 KiB

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