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.

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