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.

179 lines
4.6 KiB

10 years ago
10 years ago
10 years ago
10 years ago
  1. package weed_server
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "net/http"
  8. "path/filepath"
  9. "strconv"
  10. "strings"
  11. "time"
  12. "github.com/chrislusf/seaweedfs/go/glog"
  13. "github.com/chrislusf/seaweedfs/go/operation"
  14. "github.com/chrislusf/seaweedfs/go/security"
  15. "github.com/chrislusf/seaweedfs/go/stats"
  16. "github.com/chrislusf/seaweedfs/go/storage"
  17. "github.com/chrislusf/seaweedfs/go/util"
  18. )
  19. var serverStats *stats.ServerStats
  20. var startTime = time.Now()
  21. func init() {
  22. serverStats = stats.NewServerStats()
  23. go serverStats.Start()
  24. }
  25. func writeJson(w http.ResponseWriter, r *http.Request, httpStatus int, obj interface{}) (err error) {
  26. var bytes []byte
  27. if r.FormValue("pretty") != "" {
  28. bytes, err = json.MarshalIndent(obj, "", " ")
  29. } else {
  30. bytes, err = json.Marshal(obj)
  31. }
  32. if err != nil {
  33. return
  34. }
  35. callback := r.FormValue("callback")
  36. if callback == "" {
  37. w.Header().Set("Content-Type", "application/json")
  38. w.WriteHeader(httpStatus)
  39. _, err = w.Write(bytes)
  40. } else {
  41. w.Header().Set("Content-Type", "application/javascript")
  42. w.WriteHeader(httpStatus)
  43. if _, err = w.Write([]uint8(callback)); err != nil {
  44. return
  45. }
  46. if _, err = w.Write([]uint8("(")); err != nil {
  47. return
  48. }
  49. fmt.Fprint(w, string(bytes))
  50. if _, err = w.Write([]uint8(")")); err != nil {
  51. return
  52. }
  53. }
  54. return
  55. }
  56. // wrapper for writeJson - just logs errors
  57. func writeJsonQuiet(w http.ResponseWriter, r *http.Request, httpStatus int, obj interface{}) {
  58. if err := writeJson(w, r, httpStatus, obj); err != nil {
  59. glog.V(0).Infof("error writing JSON %s: %v", obj, err)
  60. }
  61. }
  62. func writeJsonError(w http.ResponseWriter, r *http.Request, httpStatus int, err error) {
  63. m := make(map[string]interface{})
  64. m["error"] = err.Error()
  65. writeJsonQuiet(w, r, httpStatus, m)
  66. }
  67. func debug(params ...interface{}) {
  68. glog.V(4).Infoln(params)
  69. }
  70. func submitForClientHandler(w http.ResponseWriter, r *http.Request, masterUrl string) {
  71. jwt := security.GetJwt(r)
  72. m := make(map[string]interface{})
  73. if r.Method != "POST" {
  74. writeJsonError(w, r, http.StatusMethodNotAllowed, errors.New("Only submit via POST!"))
  75. return
  76. }
  77. debug("parsing upload file...")
  78. fname, data, mimeType, isGzipped, lastModified, _, pe := storage.ParseUpload(r)
  79. if pe != nil {
  80. writeJsonError(w, r, http.StatusBadRequest, pe)
  81. return
  82. }
  83. debug("assigning file id for", fname)
  84. r.ParseForm()
  85. assignResult, ae := operation.Assign(masterUrl, 1, r.FormValue("replication"), r.FormValue("collection"), r.FormValue("ttl"))
  86. if ae != nil {
  87. writeJsonError(w, r, http.StatusInternalServerError, ae)
  88. return
  89. }
  90. url := "http://" + assignResult.Url + "/" + assignResult.Fid
  91. if lastModified != 0 {
  92. url = url + "?ts=" + strconv.FormatUint(lastModified, 10)
  93. }
  94. debug("upload file to store", url)
  95. uploadResult, err := operation.Upload(url, fname, bytes.NewReader(data), isGzipped, mimeType, jwt)
  96. if err != nil {
  97. writeJsonError(w, r, http.StatusInternalServerError, err)
  98. return
  99. }
  100. m["fileName"] = fname
  101. m["fid"] = assignResult.Fid
  102. m["fileUrl"] = assignResult.PublicUrl + "/" + assignResult.Fid
  103. m["size"] = uploadResult.Size
  104. writeJsonQuiet(w, r, http.StatusCreated, m)
  105. return
  106. }
  107. func deleteForClientHandler(w http.ResponseWriter, r *http.Request, masterUrl string) {
  108. r.ParseForm()
  109. fids := r.Form["fid"]
  110. ret, err := operation.DeleteFiles(masterUrl, fids)
  111. if err != nil {
  112. writeJsonError(w, r, http.StatusInternalServerError, err)
  113. return
  114. }
  115. writeJsonQuiet(w, r, http.StatusAccepted, ret)
  116. }
  117. func parseURLPath(path string) (vid, fid, filename, ext string, isVolumeIdOnly bool) {
  118. switch strings.Count(path, "/") {
  119. case 3:
  120. parts := strings.Split(path, "/")
  121. vid, fid, filename = parts[1], parts[2], parts[3]
  122. ext = filepath.Ext(filename)
  123. case 2:
  124. parts := strings.Split(path, "/")
  125. vid, fid = parts[1], parts[2]
  126. dotIndex := strings.LastIndex(fid, ".")
  127. if dotIndex > 0 {
  128. ext = fid[dotIndex:]
  129. fid = fid[0:dotIndex]
  130. }
  131. default:
  132. sepIndex := strings.LastIndex(path, "/")
  133. commaIndex := strings.LastIndex(path[sepIndex:], ",")
  134. if commaIndex <= 0 {
  135. vid, isVolumeIdOnly = path[sepIndex+1:], true
  136. return
  137. }
  138. dotIndex := strings.LastIndex(path[sepIndex:], ".")
  139. vid = path[sepIndex+1 : commaIndex]
  140. fid = path[commaIndex+1:]
  141. ext = ""
  142. if dotIndex > 0 {
  143. fid = path[commaIndex+1 : dotIndex]
  144. ext = path[dotIndex:]
  145. }
  146. }
  147. return
  148. }
  149. func statsCounterHandler(w http.ResponseWriter, r *http.Request) {
  150. m := make(map[string]interface{})
  151. m["Version"] = util.VERSION
  152. m["Counters"] = serverStats
  153. writeJsonQuiet(w, r, http.StatusOK, m)
  154. }
  155. func statsMemoryHandler(w http.ResponseWriter, r *http.Request) {
  156. m := make(map[string]interface{})
  157. m["Version"] = util.VERSION
  158. m["Memory"] = stats.MemStat()
  159. writeJsonQuiet(w, r, http.StatusOK, m)
  160. }