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.

350 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. "crypto/md5"
  5. "encoding/json"
  6. "errors"
  7. "fmt"
  8. "io"
  9. "io/ioutil"
  10. "mime"
  11. "net/http"
  12. "net/url"
  13. "os"
  14. filenamePath "path"
  15. "strconv"
  16. "strings"
  17. "time"
  18. "github.com/chrislusf/seaweedfs/weed/filer2"
  19. "github.com/chrislusf/seaweedfs/weed/glog"
  20. "github.com/chrislusf/seaweedfs/weed/operation"
  21. "github.com/chrislusf/seaweedfs/weed/pb/filer_pb"
  22. "github.com/chrislusf/seaweedfs/weed/security"
  23. "github.com/chrislusf/seaweedfs/weed/stats"
  24. "github.com/chrislusf/seaweedfs/weed/util"
  25. )
  26. var (
  27. OS_UID = uint32(os.Getuid())
  28. OS_GID = uint32(os.Getgid())
  29. )
  30. type FilerPostResult struct {
  31. Name string `json:"name,omitempty"`
  32. Size int64 `json:"size,omitempty"`
  33. Error string `json:"error,omitempty"`
  34. Fid string `json:"fid,omitempty"`
  35. Url string `json:"url,omitempty"`
  36. }
  37. func (fs *FilerServer) assignNewFileInfo(w http.ResponseWriter, r *http.Request, replication, collection string, dataCenter string) (fileId, urlLocation string, auth security.EncodedJwt, err error) {
  38. stats.FilerRequestCounter.WithLabelValues("assign").Inc()
  39. start := time.Now()
  40. defer func() { stats.FilerRequestHistogram.WithLabelValues("assign").Observe(time.Since(start).Seconds()) }()
  41. ar := &operation.VolumeAssignRequest{
  42. Count: 1,
  43. Replication: replication,
  44. Collection: collection,
  45. Ttl: r.URL.Query().Get("ttl"),
  46. DataCenter: dataCenter,
  47. }
  48. var altRequest *operation.VolumeAssignRequest
  49. if dataCenter != "" {
  50. altRequest = &operation.VolumeAssignRequest{
  51. Count: 1,
  52. Replication: replication,
  53. Collection: collection,
  54. Ttl: r.URL.Query().Get("ttl"),
  55. DataCenter: "",
  56. }
  57. }
  58. assignResult, ae := operation.Assign(fs.filer.GetMaster(), fs.grpcDialOption, ar, altRequest)
  59. if ae != nil {
  60. glog.Errorf("failing to assign a file id: %v", ae)
  61. writeJsonError(w, r, http.StatusInternalServerError, ae)
  62. err = ae
  63. return
  64. }
  65. fileId = assignResult.Fid
  66. urlLocation = "http://" + assignResult.Url + "/" + assignResult.Fid
  67. auth = assignResult.Auth
  68. return
  69. }
  70. func (fs *FilerServer) PostHandler(w http.ResponseWriter, r *http.Request) {
  71. ctx := context.Background()
  72. query := r.URL.Query()
  73. collection, replication := fs.detectCollection(r.RequestURI, query.Get("collection"), query.Get("replication"))
  74. dataCenter := query.Get("dataCenter")
  75. if dataCenter == "" {
  76. dataCenter = fs.option.DataCenter
  77. }
  78. if autoChunked := fs.autoChunk(ctx, w, r, replication, collection, dataCenter); autoChunked {
  79. return
  80. }
  81. if fs.option.Cipher {
  82. reply, err := fs.encrypt(ctx, w, r, replication, collection, dataCenter)
  83. if err != nil {
  84. writeJsonError(w, r, http.StatusInternalServerError, err)
  85. } else if reply != nil {
  86. writeJsonQuiet(w, r, http.StatusCreated, reply)
  87. }
  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. writeJsonError(w, r, http.StatusInternalServerError, fmt.Errorf("fail to allocate volume for %s, collection:%s, datacenter:%s", r.URL.Path, collection, dataCenter))
  94. return
  95. }
  96. glog.V(4).Infof("write %s to %v", r.URL.Path, urlLocation)
  97. u, _ := url.Parse(urlLocation)
  98. // This allows a client to generate a chunk manifest and submit it to the filer -- it is a little off
  99. // because they need to provide FIDs instead of file paths...
  100. cm, _ := strconv.ParseBool(query.Get("cm"))
  101. if cm {
  102. q := u.Query()
  103. q.Set("cm", "true")
  104. u.RawQuery = q.Encode()
  105. }
  106. glog.V(4).Infoln("post to", u)
  107. ret, err := fs.uploadToVolumeServer(r, u, auth, w, fileId)
  108. if err != nil {
  109. return
  110. }
  111. if err = fs.updateFilerStore(ctx, r, w, replication, collection, ret, fileId); err != nil {
  112. return
  113. }
  114. // send back post result
  115. reply := FilerPostResult{
  116. Name: ret.Name,
  117. Size: int64(ret.Size),
  118. Error: ret.Error,
  119. Fid: fileId,
  120. Url: urlLocation,
  121. }
  122. setEtag(w, ret.ETag)
  123. writeJsonQuiet(w, r, http.StatusCreated, reply)
  124. }
  125. // update metadata in filer store
  126. func (fs *FilerServer) updateFilerStore(ctx context.Context, r *http.Request, w http.ResponseWriter,
  127. replication string, collection string, ret *operation.UploadResult, fileId string) (err error) {
  128. stats.FilerRequestCounter.WithLabelValues("postStoreWrite").Inc()
  129. start := time.Now()
  130. defer func() {
  131. stats.FilerRequestHistogram.WithLabelValues("postStoreWrite").Observe(time.Since(start).Seconds())
  132. }()
  133. modeStr := r.URL.Query().Get("mode")
  134. if modeStr == "" {
  135. modeStr = "0660"
  136. }
  137. mode, err := strconv.ParseUint(modeStr, 8, 32)
  138. if err != nil {
  139. glog.Errorf("Invalid mode format: %s, use 0660 by default", modeStr)
  140. mode = 0660
  141. }
  142. path := r.URL.Path
  143. if strings.HasSuffix(path, "/") {
  144. if ret.Name != "" {
  145. path += ret.Name
  146. }
  147. }
  148. existingEntry, err := fs.filer.FindEntry(ctx, filer2.FullPath(path))
  149. crTime := time.Now()
  150. if err == nil && existingEntry != nil {
  151. crTime = existingEntry.Crtime
  152. }
  153. entry := &filer2.Entry{
  154. FullPath: filer2.FullPath(path),
  155. Attr: filer2.Attr{
  156. Mtime: time.Now(),
  157. Crtime: crTime,
  158. Mode: os.FileMode(mode),
  159. Uid: OS_UID,
  160. Gid: OS_GID,
  161. Replication: replication,
  162. Collection: collection,
  163. TtlSec: int32(util.ParseInt(r.URL.Query().Get("ttl"), 0)),
  164. Mime: ret.Mime,
  165. },
  166. Chunks: []*filer_pb.FileChunk{{
  167. FileId: fileId,
  168. Size: uint64(ret.Size),
  169. Mtime: time.Now().UnixNano(),
  170. ETag: ret.ETag,
  171. }},
  172. }
  173. if entry.Attr.Mime == "" {
  174. if ext := filenamePath.Ext(path); ext != "" {
  175. entry.Attr.Mime = mime.TypeByExtension(ext)
  176. }
  177. }
  178. // glog.V(4).Infof("saving %s => %+v", path, entry)
  179. if dbErr := fs.filer.CreateEntry(ctx, entry, false); dbErr != nil {
  180. fs.filer.DeleteChunks(entry.Chunks)
  181. glog.V(0).Infof("failing to write %s to filer server : %v", path, dbErr)
  182. writeJsonError(w, r, http.StatusInternalServerError, dbErr)
  183. err = dbErr
  184. return
  185. }
  186. return nil
  187. }
  188. // send request to volume server
  189. func (fs *FilerServer) uploadToVolumeServer(r *http.Request, u *url.URL, auth security.EncodedJwt, w http.ResponseWriter, fileId string) (ret *operation.UploadResult, err error) {
  190. stats.FilerRequestCounter.WithLabelValues("postUpload").Inc()
  191. start := time.Now()
  192. defer func() { stats.FilerRequestHistogram.WithLabelValues("postUpload").Observe(time.Since(start).Seconds()) }()
  193. ret = &operation.UploadResult{}
  194. hash := md5.New()
  195. var body = ioutil.NopCloser(io.TeeReader(r.Body, hash))
  196. request := &http.Request{
  197. Method: r.Method,
  198. URL: u,
  199. Proto: r.Proto,
  200. ProtoMajor: r.ProtoMajor,
  201. ProtoMinor: r.ProtoMinor,
  202. Header: r.Header,
  203. Body: body,
  204. Host: r.Host,
  205. ContentLength: r.ContentLength,
  206. }
  207. if auth != "" {
  208. request.Header.Set("Authorization", "BEARER "+string(auth))
  209. }
  210. resp, doErr := util.Do(request)
  211. if doErr != nil {
  212. glog.Errorf("failing to connect to volume server %s: %v, %+v", r.RequestURI, doErr, r.Method)
  213. writeJsonError(w, r, http.StatusInternalServerError, doErr)
  214. err = doErr
  215. return
  216. }
  217. defer func() {
  218. io.Copy(ioutil.Discard, resp.Body)
  219. resp.Body.Close()
  220. }()
  221. respBody, raErr := ioutil.ReadAll(resp.Body)
  222. if raErr != nil {
  223. glog.V(0).Infoln("failing to upload to volume server", r.RequestURI, raErr.Error())
  224. writeJsonError(w, r, http.StatusInternalServerError, raErr)
  225. err = raErr
  226. return
  227. }
  228. glog.V(4).Infoln("post result", string(respBody))
  229. unmarshalErr := json.Unmarshal(respBody, &ret)
  230. if unmarshalErr != nil {
  231. glog.V(0).Infoln("failing to read upload resonse", r.RequestURI, string(respBody))
  232. writeJsonError(w, r, http.StatusInternalServerError, unmarshalErr)
  233. err = unmarshalErr
  234. return
  235. }
  236. if ret.Error != "" {
  237. err = errors.New(ret.Error)
  238. glog.V(0).Infoln("failing to post to volume server", r.RequestURI, ret.Error)
  239. writeJsonError(w, r, http.StatusInternalServerError, err)
  240. return
  241. }
  242. // find correct final path
  243. path := r.URL.Path
  244. if strings.HasSuffix(path, "/") {
  245. if ret.Name != "" {
  246. path += ret.Name
  247. } else {
  248. err = fmt.Errorf("can not to write to folder %s without a file name", path)
  249. fs.filer.DeleteFileByFileId(fileId)
  250. glog.V(0).Infoln("Can not to write to folder", path, "without a file name!")
  251. writeJsonError(w, r, http.StatusInternalServerError, err)
  252. return
  253. }
  254. }
  255. // use filer calculated md5 ETag, instead of the volume server crc ETag
  256. ret.ETag = fmt.Sprintf("%x", hash.Sum(nil))
  257. return
  258. }
  259. // curl -X DELETE http://localhost:8888/path/to
  260. // curl -X DELETE http://localhost:8888/path/to?recursive=true
  261. // curl -X DELETE http://localhost:8888/path/to?recursive=true&ignoreRecursiveError=true
  262. // curl -X DELETE http://localhost:8888/path/to?recursive=true&skipChunkDeletion=true
  263. func (fs *FilerServer) DeleteHandler(w http.ResponseWriter, r *http.Request) {
  264. isRecursive := r.FormValue("recursive") == "true"
  265. if !isRecursive && fs.option.recursiveDelete {
  266. if r.FormValue("recursive") != "false" {
  267. isRecursive = true
  268. }
  269. }
  270. ignoreRecursiveError := r.FormValue("ignoreRecursiveError") == "true"
  271. skipChunkDeletion := r.FormValue("skipChunkDeletion") == "true"
  272. err := fs.filer.DeleteEntryMetaAndData(context.Background(), filer2.FullPath(r.URL.Path), isRecursive, ignoreRecursiveError, !skipChunkDeletion)
  273. if err != nil {
  274. glog.V(1).Infoln("deleting", r.URL.Path, ":", err.Error())
  275. httpStatus := http.StatusInternalServerError
  276. if err == filer_pb.ErrNotFound {
  277. httpStatus = http.StatusNotFound
  278. }
  279. writeJsonError(w, r, httpStatus, err)
  280. return
  281. }
  282. w.WriteHeader(http.StatusNoContent)
  283. }
  284. func (fs *FilerServer) detectCollection(requestURI, qCollection, qReplication string) (collection, replication string) {
  285. // default
  286. collection = fs.option.Collection
  287. replication = fs.option.DefaultReplication
  288. // get default collection settings
  289. if qCollection != "" {
  290. collection = qCollection
  291. }
  292. if qReplication != "" {
  293. replication = qReplication
  294. }
  295. // required by buckets folder
  296. if strings.HasPrefix(requestURI, fs.filer.DirBucketsPath+"/") {
  297. bucketAndObjectKey := requestURI[len(fs.filer.DirBucketsPath)+1:]
  298. t := strings.Index(bucketAndObjectKey, "/")
  299. if t < 0 {
  300. collection = bucketAndObjectKey
  301. }
  302. if t > 0 {
  303. collection = bucketAndObjectKey[:t]
  304. }
  305. replication = fs.filer.ReadBucketOption(collection)
  306. }
  307. return
  308. }