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.

347 lines
10 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. Mime: ret.Mime,
  164. },
  165. Chunks: []*filer_pb.FileChunk{{
  166. FileId: fileId,
  167. Size: uint64(ret.Size),
  168. Mtime: time.Now().UnixNano(),
  169. ETag: ret.ETag,
  170. }},
  171. }
  172. if entry.Attr.Mime == "" {
  173. if ext := filenamePath.Ext(path); ext != "" {
  174. entry.Attr.Mime = mime.TypeByExtension(ext)
  175. }
  176. }
  177. // glog.V(4).Infof("saving %s => %+v", path, entry)
  178. if dbErr := fs.filer.CreateEntry(ctx, entry, false); dbErr != nil {
  179. fs.filer.DeleteChunks(entry.Chunks)
  180. glog.V(0).Infof("failing to write %s to filer server : %v", path, dbErr)
  181. writeJsonError(w, r, http.StatusInternalServerError, dbErr)
  182. err = dbErr
  183. return
  184. }
  185. return nil
  186. }
  187. // send request to volume server
  188. func (fs *FilerServer) uploadToVolumeServer(r *http.Request, u *url.URL, auth security.EncodedJwt, w http.ResponseWriter, fileId string) (ret *operation.UploadResult, err error) {
  189. stats.FilerRequestCounter.WithLabelValues("postUpload").Inc()
  190. start := time.Now()
  191. defer func() { stats.FilerRequestHistogram.WithLabelValues("postUpload").Observe(time.Since(start).Seconds()) }()
  192. ret = &operation.UploadResult{}
  193. request := &http.Request{
  194. Method: r.Method,
  195. URL: u,
  196. Proto: r.Proto,
  197. ProtoMajor: r.ProtoMajor,
  198. ProtoMinor: r.ProtoMinor,
  199. Header: r.Header,
  200. Body: r.Body,
  201. Host: r.Host,
  202. ContentLength: r.ContentLength,
  203. }
  204. if auth != "" {
  205. request.Header.Set("Authorization", "BEARER "+string(auth))
  206. }
  207. resp, doErr := util.Do(request)
  208. if doErr != nil {
  209. glog.Errorf("failing to connect to volume server %s: %v, %+v", r.RequestURI, doErr, r.Method)
  210. writeJsonError(w, r, http.StatusInternalServerError, doErr)
  211. err = doErr
  212. return
  213. }
  214. defer func() {
  215. io.Copy(ioutil.Discard, resp.Body)
  216. resp.Body.Close()
  217. }()
  218. etag := resp.Header.Get("ETag")
  219. respBody, raErr := ioutil.ReadAll(resp.Body)
  220. if raErr != nil {
  221. glog.V(0).Infoln("failing to upload to volume server", r.RequestURI, raErr.Error())
  222. writeJsonError(w, r, http.StatusInternalServerError, raErr)
  223. err = raErr
  224. return
  225. }
  226. glog.V(4).Infoln("post result", string(respBody))
  227. unmarshalErr := json.Unmarshal(respBody, &ret)
  228. if unmarshalErr != nil {
  229. glog.V(0).Infoln("failing to read upload resonse", r.RequestURI, string(respBody))
  230. writeJsonError(w, r, http.StatusInternalServerError, unmarshalErr)
  231. err = unmarshalErr
  232. return
  233. }
  234. if ret.Error != "" {
  235. err = errors.New(ret.Error)
  236. glog.V(0).Infoln("failing to post to volume server", r.RequestURI, ret.Error)
  237. writeJsonError(w, r, http.StatusInternalServerError, err)
  238. return
  239. }
  240. // find correct final path
  241. path := r.URL.Path
  242. if strings.HasSuffix(path, "/") {
  243. if ret.Name != "" {
  244. path += ret.Name
  245. } else {
  246. err = fmt.Errorf("can not to write to folder %s without a file name", path)
  247. fs.filer.DeleteFileByFileId(fileId)
  248. glog.V(0).Infoln("Can not to write to folder", path, "without a file name!")
  249. writeJsonError(w, r, http.StatusInternalServerError, err)
  250. return
  251. }
  252. }
  253. if etag != "" {
  254. ret.ETag = etag
  255. }
  256. return
  257. }
  258. // curl -X DELETE http://localhost:8888/path/to
  259. // curl -X DELETE http://localhost:8888/path/to?recursive=true
  260. // curl -X DELETE http://localhost:8888/path/to?recursive=true&ignoreRecursiveError=true
  261. // curl -X DELETE http://localhost:8888/path/to?recursive=true&skipChunkDeletion=true
  262. func (fs *FilerServer) DeleteHandler(w http.ResponseWriter, r *http.Request) {
  263. isRecursive := r.FormValue("recursive") == "true"
  264. if !isRecursive && fs.option.recursiveDelete {
  265. if r.FormValue("recursive") != "false" {
  266. isRecursive = true
  267. }
  268. }
  269. ignoreRecursiveError := r.FormValue("ignoreRecursiveError") == "true"
  270. skipChunkDeletion := r.FormValue("skipChunkDeletion") == "true"
  271. err := fs.filer.DeleteEntryMetaAndData(context.Background(), filer2.FullPath(r.URL.Path), isRecursive, ignoreRecursiveError, !skipChunkDeletion)
  272. if err != nil {
  273. glog.V(1).Infoln("deleting", r.URL.Path, ":", err.Error())
  274. httpStatus := http.StatusInternalServerError
  275. if err == filer2.ErrNotFound {
  276. httpStatus = http.StatusNotFound
  277. }
  278. writeJsonError(w, r, httpStatus, err)
  279. return
  280. }
  281. w.WriteHeader(http.StatusNoContent)
  282. }
  283. func (fs *FilerServer) detectCollection(requestURI, qCollection, qReplication string) (collection, replication string) {
  284. // default
  285. collection = fs.option.Collection
  286. replication = fs.option.DefaultReplication
  287. // get default collection settings
  288. if qCollection != "" {
  289. collection = qCollection
  290. }
  291. if qReplication != "" {
  292. replication = qReplication
  293. }
  294. // required by buckets folder
  295. if strings.HasPrefix(requestURI, fs.filer.DirBucketsPath+"/") {
  296. bucketAndObjectKey := requestURI[len(fs.filer.DirBucketsPath)+1:]
  297. t := strings.Index(bucketAndObjectKey, "/")
  298. if t < 0 {
  299. collection = bucketAndObjectKey
  300. }
  301. if t > 0 {
  302. collection = bucketAndObjectKey[:t]
  303. }
  304. replication = fs.filer.ReadBucketOption(collection)
  305. }
  306. return
  307. }