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.

204 lines
5.4 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. m["eTag"] = uploadResult.ETag
  112. writeJsonQuiet(w, r, http.StatusCreated, m)
  113. return
  114. }
  115. func deleteForClientHandler(w http.ResponseWriter, r *http.Request, masterUrl string) {
  116. r.ParseForm()
  117. fids := r.Form["fid"]
  118. ret, err := operation.DeleteFiles(masterUrl, fids)
  119. if err != nil {
  120. writeJsonError(w, r, http.StatusInternalServerError, err)
  121. return
  122. }
  123. writeJsonQuiet(w, r, http.StatusAccepted, ret)
  124. }
  125. func parseURLPath(path string) (vid, fid, filename, ext string, isVolumeIdOnly bool) {
  126. switch strings.Count(path, "/") {
  127. case 3:
  128. parts := strings.Split(path, "/")
  129. vid, fid, filename = parts[1], parts[2], parts[3]
  130. ext = filepath.Ext(filename)
  131. case 2:
  132. parts := strings.Split(path, "/")
  133. vid, fid = parts[1], parts[2]
  134. dotIndex := strings.LastIndex(fid, ".")
  135. if dotIndex > 0 {
  136. ext = fid[dotIndex:]
  137. fid = fid[0:dotIndex]
  138. }
  139. default:
  140. sepIndex := strings.LastIndex(path, "/")
  141. commaIndex := strings.LastIndex(path[sepIndex:], ",")
  142. if commaIndex <= 0 {
  143. vid, isVolumeIdOnly = path[sepIndex+1:], true
  144. return
  145. }
  146. dotIndex := strings.LastIndex(path[sepIndex:], ".")
  147. vid = path[sepIndex+1 : commaIndex]
  148. fid = path[commaIndex+1:]
  149. ext = ""
  150. if dotIndex > 0 {
  151. fid = path[commaIndex+1 : dotIndex]
  152. ext = path[dotIndex:]
  153. }
  154. }
  155. return
  156. }
  157. func statsHealthHandler(w http.ResponseWriter, r *http.Request) {
  158. m := make(map[string]interface{})
  159. m["Version"] = util.VERSION
  160. writeJsonQuiet(w, r, http.StatusOK, m)
  161. }
  162. func statsCounterHandler(w http.ResponseWriter, r *http.Request) {
  163. m := make(map[string]interface{})
  164. m["Version"] = util.VERSION
  165. m["Counters"] = serverStats
  166. writeJsonQuiet(w, r, http.StatusOK, m)
  167. }
  168. func statsMemoryHandler(w http.ResponseWriter, r *http.Request) {
  169. m := make(map[string]interface{})
  170. m["Version"] = util.VERSION
  171. m["Memory"] = stats.MemStat()
  172. writeJsonQuiet(w, r, http.StatusOK, m)
  173. }
  174. func faviconHandler(w http.ResponseWriter, r *http.Request) {
  175. data, err := images.Asset("favicon/favicon.ico")
  176. if err != nil {
  177. glog.V(2).Infoln("favicon read error:", err)
  178. return
  179. }
  180. if e := writeResponseContent("favicon.ico", "image/x-icon", bytes.NewReader(data), w, r); e != nil {
  181. glog.V(2).Infoln("response write error:", e)
  182. }
  183. }