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.

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