filer_server_handlers_write.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  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 int64 `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: int64(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. modeStr := r.URL.Query().Get("mode")
  130. if modeStr == "" {
  131. modeStr = "0660"
  132. }
  133. mode, err := strconv.ParseUint(modeStr, 8, 32)
  134. if err != nil {
  135. glog.Errorf("Invalid mode format: %s, use 0660 by default", modeStr)
  136. mode = 0660
  137. }
  138. path := r.URL.Path
  139. if strings.HasSuffix(path, "/") {
  140. if ret.Name != "" {
  141. path += ret.Name
  142. }
  143. }
  144. existingEntry, err := fs.filer.FindEntry(ctx, filer2.FullPath(path))
  145. crTime := time.Now()
  146. if err == nil && existingEntry != nil {
  147. crTime = existingEntry.Crtime
  148. }
  149. entry := &filer2.Entry{
  150. FullPath: filer2.FullPath(path),
  151. Attr: filer2.Attr{
  152. Mtime: time.Now(),
  153. Crtime: crTime,
  154. Mode: os.FileMode(mode),
  155. Uid: OS_UID,
  156. Gid: OS_GID,
  157. Replication: replication,
  158. Collection: collection,
  159. TtlSec: int32(util.ParseInt(r.URL.Query().Get("ttl"), 0)),
  160. },
  161. Chunks: []*filer_pb.FileChunk{{
  162. FileId: fileId,
  163. Size: uint64(ret.Size),
  164. Mtime: time.Now().UnixNano(),
  165. ETag: ret.ETag,
  166. }},
  167. }
  168. if ext := filenamePath.Ext(path); ext != "" {
  169. entry.Attr.Mime = mime.TypeByExtension(ext)
  170. }
  171. // glog.V(4).Infof("saving %s => %+v", path, entry)
  172. if dbErr := fs.filer.CreateEntry(ctx, entry, false); dbErr != nil {
  173. fs.filer.DeleteChunks(entry.Chunks)
  174. glog.V(0).Infof("failing to write %s to filer server : %v", path, dbErr)
  175. writeJsonError(w, r, http.StatusInternalServerError, dbErr)
  176. err = dbErr
  177. return
  178. }
  179. return nil
  180. }
  181. // send request to volume server
  182. func (fs *FilerServer) uploadToVolumeServer(r *http.Request, u *url.URL, auth security.EncodedJwt, w http.ResponseWriter, fileId string) (ret operation.UploadResult, err error) {
  183. stats.FilerRequestCounter.WithLabelValues("postUpload").Inc()
  184. start := time.Now()
  185. defer func() { stats.FilerRequestHistogram.WithLabelValues("postUpload").Observe(time.Since(start).Seconds()) }()
  186. request := &http.Request{
  187. Method: r.Method,
  188. URL: u,
  189. Proto: r.Proto,
  190. ProtoMajor: r.ProtoMajor,
  191. ProtoMinor: r.ProtoMinor,
  192. Header: r.Header,
  193. Body: r.Body,
  194. Host: r.Host,
  195. ContentLength: r.ContentLength,
  196. }
  197. if auth != "" {
  198. request.Header.Set("Authorization", "BEARER "+string(auth))
  199. }
  200. resp, doErr := util.Do(request)
  201. if doErr != nil {
  202. glog.Errorf("failing to connect to volume server %s: %v, %+v", r.RequestURI, doErr, r.Method)
  203. writeJsonError(w, r, http.StatusInternalServerError, doErr)
  204. err = doErr
  205. return
  206. }
  207. defer func() {
  208. io.Copy(ioutil.Discard, resp.Body)
  209. resp.Body.Close()
  210. }()
  211. etag := resp.Header.Get("ETag")
  212. respBody, raErr := ioutil.ReadAll(resp.Body)
  213. if raErr != nil {
  214. glog.V(0).Infoln("failing to upload to volume server", r.RequestURI, raErr.Error())
  215. writeJsonError(w, r, http.StatusInternalServerError, raErr)
  216. err = raErr
  217. return
  218. }
  219. glog.V(4).Infoln("post result", string(respBody))
  220. unmarshalErr := json.Unmarshal(respBody, &ret)
  221. if unmarshalErr != nil {
  222. glog.V(0).Infoln("failing to read upload resonse", r.RequestURI, string(respBody))
  223. writeJsonError(w, r, http.StatusInternalServerError, unmarshalErr)
  224. err = unmarshalErr
  225. return
  226. }
  227. if ret.Error != "" {
  228. err = errors.New(ret.Error)
  229. glog.V(0).Infoln("failing to post to volume server", r.RequestURI, ret.Error)
  230. writeJsonError(w, r, http.StatusInternalServerError, err)
  231. return
  232. }
  233. // find correct final path
  234. path := r.URL.Path
  235. if strings.HasSuffix(path, "/") {
  236. if ret.Name != "" {
  237. path += ret.Name
  238. } else {
  239. err = fmt.Errorf("can not to write to folder %s without a file name", path)
  240. fs.filer.DeleteFileByFileId(fileId)
  241. glog.V(0).Infoln("Can not to write to folder", path, "without a file name!")
  242. writeJsonError(w, r, http.StatusInternalServerError, err)
  243. return
  244. }
  245. }
  246. if etag != "" {
  247. ret.ETag = etag
  248. }
  249. return
  250. }
  251. // curl -X DELETE http://localhost:8888/path/to
  252. // curl -X DELETE http://localhost:8888/path/to?recursive=true
  253. // curl -X DELETE http://localhost:8888/path/to?recursive=true&ignoreRecursiveError=true
  254. // curl -X DELETE http://localhost:8888/path/to?recursive=true&skipChunkDeletion=true
  255. func (fs *FilerServer) DeleteHandler(w http.ResponseWriter, r *http.Request) {
  256. isRecursive := r.FormValue("recursive") == "true"
  257. if !isRecursive && fs.option.recursiveDelete {
  258. if r.FormValue("recursive") != "false" {
  259. isRecursive = true
  260. }
  261. }
  262. ignoreRecursiveError := r.FormValue("ignoreRecursiveError") == "true"
  263. skipChunkDeletion := r.FormValue("skipChunkDeletion") == "true"
  264. err := fs.filer.DeleteEntryMetaAndData(context.Background(), filer2.FullPath(r.URL.Path), isRecursive, ignoreRecursiveError, !skipChunkDeletion)
  265. if err != nil {
  266. glog.V(1).Infoln("deleting", r.URL.Path, ":", err.Error())
  267. httpStatus := http.StatusInternalServerError
  268. if err == filer2.ErrNotFound {
  269. httpStatus = http.StatusNotFound
  270. }
  271. writeJsonError(w, r, httpStatus, err)
  272. return
  273. }
  274. w.WriteHeader(http.StatusNoContent)
  275. }