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.

292 lines
8.5 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
6 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. "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. stats.FilerRequestCounter.WithLabelValues("post").Inc()
  71. start := time.Now()
  72. defer func() { stats.FilerRequestHistogram.WithLabelValues("post").Observe(time.Since(start).Seconds()) }()
  73. ctx := context.Background()
  74. query := r.URL.Query()
  75. replication := query.Get("replication")
  76. if replication == "" {
  77. replication = fs.option.DefaultReplication
  78. }
  79. collection := query.Get("collection")
  80. if collection == "" {
  81. collection = fs.option.Collection
  82. }
  83. dataCenter := query.Get("dataCenter")
  84. if dataCenter == "" {
  85. dataCenter = fs.option.DataCenter
  86. }
  87. if autoChunked := fs.autoChunk(ctx, w, r, replication, collection, dataCenter); autoChunked {
  88. return
  89. }
  90. fileId, urlLocation, auth, err := fs.assignNewFileInfo(w, r, replication, collection, dataCenter)
  91. if err != nil || fileId == "" || urlLocation == "" {
  92. glog.V(0).Infof("fail to allocate volume for %s, collection:%s, datacenter:%s", r.URL.Path, collection, dataCenter)
  93. return
  94. }
  95. glog.V(4).Infof("write %s to %v", r.URL.Path, urlLocation)
  96. u, _ := url.Parse(urlLocation)
  97. // This allows a client to generate a chunk manifest and submit it to the filer -- it is a little off
  98. // because they need to provide FIDs instead of file paths...
  99. cm, _ := strconv.ParseBool(query.Get("cm"))
  100. if cm {
  101. q := u.Query()
  102. q.Set("cm", "true")
  103. u.RawQuery = q.Encode()
  104. }
  105. glog.V(4).Infoln("post to", u)
  106. ret, err := fs.uploadToVolumeServer(r, u, auth, w, fileId)
  107. if err != nil {
  108. return
  109. }
  110. if err = fs.updateFilerStore(ctx, r, w, replication, collection, ret, fileId); err != nil {
  111. return
  112. }
  113. // send back post result
  114. reply := FilerPostResult{
  115. Name: ret.Name,
  116. Size: ret.Size,
  117. Error: ret.Error,
  118. Fid: fileId,
  119. Url: urlLocation,
  120. }
  121. setEtag(w, ret.ETag)
  122. writeJsonQuiet(w, r, http.StatusCreated, reply)
  123. }
  124. // update metadata in filer store
  125. func (fs *FilerServer) updateFilerStore(ctx context.Context, r *http.Request, w http.ResponseWriter,
  126. replication string, collection string, ret operation.UploadResult, fileId string) (err error) {
  127. stats.FilerRequestCounter.WithLabelValues("postStoreWrite").Inc()
  128. start := time.Now()
  129. defer func() {
  130. stats.FilerRequestHistogram.WithLabelValues("postStoreWrite").Observe(time.Since(start).Seconds())
  131. }()
  132. path := r.URL.Path
  133. existingEntry, err := fs.filer.FindEntry(ctx, filer2.FullPath(path))
  134. crTime := time.Now()
  135. if err == nil && existingEntry != nil {
  136. // glog.V(4).Infof("existing %s => %+v", path, existingEntry)
  137. if existingEntry.IsDirectory() {
  138. path += "/" + ret.Name
  139. } else {
  140. crTime = existingEntry.Crtime
  141. }
  142. }
  143. entry := &filer2.Entry{
  144. FullPath: filer2.FullPath(path),
  145. Attr: filer2.Attr{
  146. Mtime: time.Now(),
  147. Crtime: crTime,
  148. Mode: 0660,
  149. Uid: OS_UID,
  150. Gid: OS_GID,
  151. Replication: replication,
  152. Collection: collection,
  153. TtlSec: int32(util.ParseInt(r.URL.Query().Get("ttl"), 0)),
  154. },
  155. Chunks: []*filer_pb.FileChunk{{
  156. FileId: fileId,
  157. Size: uint64(ret.Size),
  158. Mtime: time.Now().UnixNano(),
  159. ETag: ret.ETag,
  160. }},
  161. }
  162. if ext := filenamePath.Ext(path); ext != "" {
  163. entry.Attr.Mime = mime.TypeByExtension(ext)
  164. }
  165. // glog.V(4).Infof("saving %s => %+v", path, entry)
  166. if dbErr := fs.filer.CreateEntry(ctx, entry); dbErr != nil {
  167. fs.filer.DeleteChunks(entry.FullPath, entry.Chunks)
  168. glog.V(0).Infof("failing to write %s to filer server : %v", path, dbErr)
  169. writeJsonError(w, r, http.StatusInternalServerError, dbErr)
  170. err = dbErr
  171. return
  172. }
  173. return nil
  174. }
  175. // send request to volume server
  176. func (fs *FilerServer) uploadToVolumeServer(r *http.Request, u *url.URL, auth security.EncodedJwt, w http.ResponseWriter, fileId string) (ret operation.UploadResult, err error) {
  177. stats.FilerRequestCounter.WithLabelValues("postUpload").Inc()
  178. start := time.Now()
  179. defer func() { stats.FilerRequestHistogram.WithLabelValues("postUpload").Observe(time.Since(start).Seconds()) }()
  180. request := &http.Request{
  181. Method: r.Method,
  182. URL: u,
  183. Proto: r.Proto,
  184. ProtoMajor: r.ProtoMajor,
  185. ProtoMinor: r.ProtoMinor,
  186. Header: r.Header,
  187. Body: r.Body,
  188. Host: r.Host,
  189. ContentLength: r.ContentLength,
  190. }
  191. if auth != "" {
  192. request.Header.Set("Authorization", "BEARER "+string(auth))
  193. }
  194. resp, doErr := util.Do(request)
  195. if doErr != nil {
  196. glog.Errorf("failing to connect to volume server %s: %v, %+v", r.RequestURI, doErr, r.Method)
  197. writeJsonError(w, r, http.StatusInternalServerError, doErr)
  198. err = doErr
  199. return
  200. }
  201. defer func() {
  202. io.Copy(ioutil.Discard, resp.Body)
  203. resp.Body.Close()
  204. }()
  205. etag := resp.Header.Get("ETag")
  206. respBody, raErr := ioutil.ReadAll(resp.Body)
  207. if raErr != nil {
  208. glog.V(0).Infoln("failing to upload to volume server", r.RequestURI, raErr.Error())
  209. writeJsonError(w, r, http.StatusInternalServerError, raErr)
  210. err = raErr
  211. return
  212. }
  213. glog.V(4).Infoln("post result", string(respBody))
  214. unmarshalErr := json.Unmarshal(respBody, &ret)
  215. if unmarshalErr != nil {
  216. glog.V(0).Infoln("failing to read upload resonse", r.RequestURI, string(respBody))
  217. writeJsonError(w, r, http.StatusInternalServerError, unmarshalErr)
  218. err = unmarshalErr
  219. return
  220. }
  221. if ret.Error != "" {
  222. err = errors.New(ret.Error)
  223. glog.V(0).Infoln("failing to post to volume server", r.RequestURI, ret.Error)
  224. writeJsonError(w, r, http.StatusInternalServerError, err)
  225. return
  226. }
  227. // find correct final path
  228. path := r.URL.Path
  229. if strings.HasSuffix(path, "/") {
  230. if ret.Name != "" {
  231. path += ret.Name
  232. } else {
  233. err = fmt.Errorf("can not to write to folder %s without a file name", path)
  234. fs.filer.DeleteFileByFileId(fileId)
  235. glog.V(0).Infoln("Can not to write to folder", path, "without a file name!")
  236. writeJsonError(w, r, http.StatusInternalServerError, err)
  237. return
  238. }
  239. }
  240. if etag != "" {
  241. ret.ETag = etag
  242. }
  243. return
  244. }
  245. // curl -X DELETE http://localhost:8888/path/to
  246. // curl -X DELETE http://localhost:8888/path/to?recursive=true
  247. func (fs *FilerServer) DeleteHandler(w http.ResponseWriter, r *http.Request) {
  248. stats.FilerRequestCounter.WithLabelValues("delete").Inc()
  249. start := time.Now()
  250. defer func() { stats.FilerRequestHistogram.WithLabelValues("delete").Observe(time.Since(start).Seconds()) }()
  251. isRecursive := r.FormValue("recursive") == "true"
  252. err := fs.filer.DeleteEntryMetaAndData(context.Background(), filer2.FullPath(r.URL.Path), isRecursive, true)
  253. if err != nil {
  254. glog.V(1).Infoln("deleting", r.URL.Path, ":", err.Error())
  255. writeJsonError(w, r, http.StatusInternalServerError, err)
  256. return
  257. }
  258. w.WriteHeader(http.StatusNoContent)
  259. }