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.

212 lines
5.7 KiB

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