filer_server_handlers_write.go 8.2 KB

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