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.

201 lines
5.4 KiB

10 years ago
6 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/stats"
  15. "github.com/chrislusf/seaweedfs/weed/storage"
  16. "github.com/chrislusf/seaweedfs/weed/util"
  17. _ "github.com/chrislusf/seaweedfs/weed/statik"
  18. "github.com/gorilla/mux"
  19. statik "github.com/rakyll/statik/fs"
  20. )
  21. var serverStats *stats.ServerStats
  22. var startTime = time.Now()
  23. var statikFS http.FileSystem
  24. func init() {
  25. serverStats = stats.NewServerStats()
  26. go serverStats.Start()
  27. statikFS, _ = statik.New()
  28. }
  29. func writeJson(w http.ResponseWriter, r *http.Request, httpStatus int, obj interface{}) (err error) {
  30. var bytes []byte
  31. if r.FormValue("pretty") != "" {
  32. bytes, err = json.MarshalIndent(obj, "", " ")
  33. } else {
  34. bytes, err = json.Marshal(obj)
  35. }
  36. if err != nil {
  37. return
  38. }
  39. callback := r.FormValue("callback")
  40. if callback == "" {
  41. w.Header().Set("Content-Type", "application/json")
  42. w.WriteHeader(httpStatus)
  43. _, err = w.Write(bytes)
  44. } else {
  45. w.Header().Set("Content-Type", "application/javascript")
  46. w.WriteHeader(httpStatus)
  47. if _, err = w.Write([]uint8(callback)); err != nil {
  48. return
  49. }
  50. if _, err = w.Write([]uint8("(")); err != nil {
  51. return
  52. }
  53. fmt.Fprint(w, string(bytes))
  54. if _, err = w.Write([]uint8(")")); err != nil {
  55. return
  56. }
  57. }
  58. return
  59. }
  60. // wrapper for writeJson - just logs errors
  61. func writeJsonQuiet(w http.ResponseWriter, r *http.Request, httpStatus int, obj interface{}) {
  62. if err := writeJson(w, r, httpStatus, obj); err != nil {
  63. glog.V(0).Infof("error writing JSON %+v status %d: %v", obj, httpStatus, err)
  64. }
  65. }
  66. func writeJsonError(w http.ResponseWriter, r *http.Request, httpStatus int, err error) {
  67. m := make(map[string]interface{})
  68. m["error"] = err.Error()
  69. writeJsonQuiet(w, r, httpStatus, m)
  70. }
  71. func debug(params ...interface{}) {
  72. glog.V(4).Infoln(params...)
  73. }
  74. func submitForClientHandler(w http.ResponseWriter, r *http.Request, masterUrl string) {
  75. m := make(map[string]interface{})
  76. if r.Method != "POST" {
  77. writeJsonError(w, r, http.StatusMethodNotAllowed, errors.New("Only submit via POST!"))
  78. return
  79. }
  80. debug("parsing upload file...")
  81. fname, data, mimeType, pairMap, isGzipped, originalDataSize, lastModified, _, _, pe := storage.ParseUpload(r)
  82. if pe != nil {
  83. writeJsonError(w, r, http.StatusBadRequest, pe)
  84. return
  85. }
  86. debug("assigning file id for", fname)
  87. r.ParseForm()
  88. count := uint64(1)
  89. if r.FormValue("count") != "" {
  90. count, pe = strconv.ParseUint(r.FormValue("count"), 10, 32)
  91. if pe != nil {
  92. writeJsonError(w, r, http.StatusBadRequest, pe)
  93. return
  94. }
  95. }
  96. ar := &operation.VolumeAssignRequest{
  97. Count: count,
  98. Replication: r.FormValue("replication"),
  99. Collection: r.FormValue("collection"),
  100. Ttl: r.FormValue("ttl"),
  101. }
  102. assignResult, ae := operation.Assign(masterUrl, ar)
  103. if ae != nil {
  104. writeJsonError(w, r, http.StatusInternalServerError, ae)
  105. return
  106. }
  107. url := "http://" + assignResult.Url + "/" + assignResult.Fid
  108. if lastModified != 0 {
  109. url = url + "?ts=" + strconv.FormatUint(lastModified, 10)
  110. }
  111. debug("upload file to store", url)
  112. uploadResult, err := operation.Upload(url, fname, bytes.NewReader(data), isGzipped, mimeType, pairMap, assignResult.Auth)
  113. if err != nil {
  114. writeJsonError(w, r, http.StatusInternalServerError, err)
  115. return
  116. }
  117. m["fileName"] = fname
  118. m["fid"] = assignResult.Fid
  119. m["fileUrl"] = assignResult.PublicUrl + "/" + assignResult.Fid
  120. m["size"] = originalDataSize
  121. m["eTag"] = uploadResult.ETag
  122. writeJsonQuiet(w, r, http.StatusCreated, m)
  123. return
  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 handleStaticResources(defaultMux *http.ServeMux) {
  175. defaultMux.Handle("/favicon.ico", http.FileServer(statikFS))
  176. defaultMux.Handle("/seaweedfsstatic/", http.StripPrefix("/seaweedfsstatic", http.FileServer(statikFS)))
  177. }
  178. func handleStaticResources2(r *mux.Router) {
  179. r.Handle("/favicon.ico", http.FileServer(statikFS))
  180. r.PathPrefix("/seaweedfsstatic/").Handler(http.StripPrefix("/seaweedfsstatic", http.FileServer(statikFS)))
  181. }