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.

203 lines
5.3 KiB

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