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.

284 lines
8.1 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
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
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. 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. existingEntry, err := fs.filer.FindEntry(ctx, filer2.FullPath(path))
  131. crTime := time.Now()
  132. if err == nil && existingEntry != nil {
  133. // glog.V(4).Infof("existing %s => %+v", path, existingEntry)
  134. if existingEntry.IsDirectory() {
  135. path += "/" + ret.Name
  136. } else {
  137. crTime = existingEntry.Crtime
  138. }
  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. func (fs *FilerServer) DeleteHandler(w http.ResponseWriter, r *http.Request) {
  245. isRecursive := r.FormValue("recursive") == "true"
  246. err := fs.filer.DeleteEntryMetaAndData(context.Background(), filer2.FullPath(r.URL.Path), isRecursive, true)
  247. if err != nil {
  248. glog.V(1).Infoln("deleting", r.URL.Path, ":", err.Error())
  249. writeJsonError(w, r, http.StatusInternalServerError, err)
  250. return
  251. }
  252. w.WriteHeader(http.StatusNoContent)
  253. }