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.

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