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.

344 lines
9.9 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
6 years ago
9 years ago
9 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 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. collection, replication := fs.detectCollection(r.RequestURI, query.Get("collection"), query.Get("replication"))
  73. dataCenter := query.Get("dataCenter")
  74. if dataCenter == "" {
  75. dataCenter = fs.option.DataCenter
  76. }
  77. if autoChunked := fs.autoChunk(ctx, w, r, replication, collection, dataCenter); autoChunked {
  78. return
  79. }
  80. if fs.option.Cipher {
  81. reply, err := fs.encrypt(ctx, w, r, replication, collection, dataCenter)
  82. if err != nil {
  83. writeJsonError(w, r, http.StatusInternalServerError, err)
  84. } else if reply != nil {
  85. writeJsonQuiet(w, r, http.StatusCreated, reply)
  86. }
  87. return
  88. }
  89. fileId, urlLocation, auth, err := fs.assignNewFileInfo(w, r, replication, collection, dataCenter)
  90. if err != nil || fileId == "" || urlLocation == "" {
  91. glog.V(0).Infof("fail to allocate volume for %s, collection:%s, datacenter:%s", r.URL.Path, collection, dataCenter)
  92. writeJsonError(w, r, http.StatusInternalServerError, fmt.Errorf("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: int64(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. modeStr := r.URL.Query().Get("mode")
  133. if modeStr == "" {
  134. modeStr = "0660"
  135. }
  136. mode, err := strconv.ParseUint(modeStr, 8, 32)
  137. if err != nil {
  138. glog.Errorf("Invalid mode format: %s, use 0660 by default", modeStr)
  139. mode = 0660
  140. }
  141. path := r.URL.Path
  142. if strings.HasSuffix(path, "/") {
  143. if ret.Name != "" {
  144. path += ret.Name
  145. }
  146. }
  147. existingEntry, err := fs.filer.FindEntry(ctx, filer2.FullPath(path))
  148. crTime := time.Now()
  149. if err == nil && existingEntry != nil {
  150. crTime = existingEntry.Crtime
  151. }
  152. entry := &filer2.Entry{
  153. FullPath: filer2.FullPath(path),
  154. Attr: filer2.Attr{
  155. Mtime: time.Now(),
  156. Crtime: crTime,
  157. Mode: os.FileMode(mode),
  158. Uid: OS_UID,
  159. Gid: OS_GID,
  160. Replication: replication,
  161. Collection: collection,
  162. TtlSec: int32(util.ParseInt(r.URL.Query().Get("ttl"), 0)),
  163. },
  164. Chunks: []*filer_pb.FileChunk{{
  165. FileId: fileId,
  166. Size: uint64(ret.Size),
  167. Mtime: time.Now().UnixNano(),
  168. ETag: ret.ETag,
  169. }},
  170. }
  171. if ext := filenamePath.Ext(path); ext != "" {
  172. entry.Attr.Mime = mime.TypeByExtension(ext)
  173. }
  174. // glog.V(4).Infof("saving %s => %+v", path, entry)
  175. if dbErr := fs.filer.CreateEntry(ctx, entry, false); dbErr != nil {
  176. fs.filer.DeleteChunks(entry.Chunks)
  177. glog.V(0).Infof("failing to write %s to filer server : %v", path, dbErr)
  178. writeJsonError(w, r, http.StatusInternalServerError, dbErr)
  179. err = dbErr
  180. return
  181. }
  182. return nil
  183. }
  184. // send request to volume server
  185. func (fs *FilerServer) uploadToVolumeServer(r *http.Request, u *url.URL, auth security.EncodedJwt, w http.ResponseWriter, fileId string) (ret *operation.UploadResult, err error) {
  186. stats.FilerRequestCounter.WithLabelValues("postUpload").Inc()
  187. start := time.Now()
  188. defer func() { stats.FilerRequestHistogram.WithLabelValues("postUpload").Observe(time.Since(start).Seconds()) }()
  189. ret = &operation.UploadResult{}
  190. request := &http.Request{
  191. Method: r.Method,
  192. URL: u,
  193. Proto: r.Proto,
  194. ProtoMajor: r.ProtoMajor,
  195. ProtoMinor: r.ProtoMinor,
  196. Header: r.Header,
  197. Body: r.Body,
  198. Host: r.Host,
  199. ContentLength: r.ContentLength,
  200. }
  201. if auth != "" {
  202. request.Header.Set("Authorization", "BEARER "+string(auth))
  203. }
  204. resp, doErr := util.Do(request)
  205. if doErr != nil {
  206. glog.Errorf("failing to connect to volume server %s: %v, %+v", r.RequestURI, doErr, r.Method)
  207. writeJsonError(w, r, http.StatusInternalServerError, doErr)
  208. err = doErr
  209. return
  210. }
  211. defer func() {
  212. io.Copy(ioutil.Discard, resp.Body)
  213. resp.Body.Close()
  214. }()
  215. etag := resp.Header.Get("ETag")
  216. respBody, raErr := ioutil.ReadAll(resp.Body)
  217. if raErr != nil {
  218. glog.V(0).Infoln("failing to upload to volume server", r.RequestURI, raErr.Error())
  219. writeJsonError(w, r, http.StatusInternalServerError, raErr)
  220. err = raErr
  221. return
  222. }
  223. glog.V(4).Infoln("post result", string(respBody))
  224. unmarshalErr := json.Unmarshal(respBody, &ret)
  225. if unmarshalErr != nil {
  226. glog.V(0).Infoln("failing to read upload resonse", r.RequestURI, string(respBody))
  227. writeJsonError(w, r, http.StatusInternalServerError, unmarshalErr)
  228. err = unmarshalErr
  229. return
  230. }
  231. if ret.Error != "" {
  232. err = errors.New(ret.Error)
  233. glog.V(0).Infoln("failing to post to volume server", r.RequestURI, ret.Error)
  234. writeJsonError(w, r, http.StatusInternalServerError, err)
  235. return
  236. }
  237. // find correct final path
  238. path := r.URL.Path
  239. if strings.HasSuffix(path, "/") {
  240. if ret.Name != "" {
  241. path += ret.Name
  242. } else {
  243. err = fmt.Errorf("can not to write to folder %s without a file name", path)
  244. fs.filer.DeleteFileByFileId(fileId)
  245. glog.V(0).Infoln("Can not to write to folder", path, "without a file name!")
  246. writeJsonError(w, r, http.StatusInternalServerError, err)
  247. return
  248. }
  249. }
  250. if etag != "" {
  251. ret.ETag = etag
  252. }
  253. return
  254. }
  255. // curl -X DELETE http://localhost:8888/path/to
  256. // curl -X DELETE http://localhost:8888/path/to?recursive=true
  257. // curl -X DELETE http://localhost:8888/path/to?recursive=true&ignoreRecursiveError=true
  258. // curl -X DELETE http://localhost:8888/path/to?recursive=true&skipChunkDeletion=true
  259. func (fs *FilerServer) DeleteHandler(w http.ResponseWriter, r *http.Request) {
  260. isRecursive := r.FormValue("recursive") == "true"
  261. if !isRecursive && fs.option.recursiveDelete {
  262. if r.FormValue("recursive") != "false" {
  263. isRecursive = true
  264. }
  265. }
  266. ignoreRecursiveError := r.FormValue("ignoreRecursiveError") == "true"
  267. skipChunkDeletion := r.FormValue("skipChunkDeletion") == "true"
  268. err := fs.filer.DeleteEntryMetaAndData(context.Background(), filer2.FullPath(r.URL.Path), isRecursive, ignoreRecursiveError, !skipChunkDeletion)
  269. if err != nil {
  270. glog.V(1).Infoln("deleting", r.URL.Path, ":", err.Error())
  271. httpStatus := http.StatusInternalServerError
  272. if err == filer2.ErrNotFound {
  273. httpStatus = http.StatusNotFound
  274. }
  275. writeJsonError(w, r, httpStatus, err)
  276. return
  277. }
  278. w.WriteHeader(http.StatusNoContent)
  279. }
  280. func (fs *FilerServer) detectCollection(requestURI, qCollection, qReplication string) (collection, replication string) {
  281. // default
  282. collection = fs.option.Collection
  283. replication = fs.option.DefaultReplication
  284. // get default collection settings
  285. if qCollection != "" {
  286. collection = qCollection
  287. }
  288. if qReplication != "" {
  289. replication = qReplication
  290. }
  291. // required by buckets folder
  292. if strings.HasPrefix(requestURI, fs.filer.DirBucketsPath+"/") {
  293. bucketAndObjectKey := requestURI[len(fs.filer.DirBucketsPath)+1:]
  294. t := strings.Index(bucketAndObjectKey, "/")
  295. if t < 0 {
  296. collection = bucketAndObjectKey
  297. }
  298. if t > 0 {
  299. collection = bucketAndObjectKey[:t]
  300. }
  301. replication = fs.filer.ReadBucketOption(collection)
  302. }
  303. return
  304. }