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.

211 lines
5.7 KiB

10 years ago
6 years ago
6 years ago
10 years ago
6 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/storage/needle"
  13. "google.golang.org/grpc"
  14. _ "github.com/chrislusf/seaweedfs/weed/storage/backend/s3_backend"
  15. "github.com/chrislusf/seaweedfs/weed/glog"
  16. "github.com/chrislusf/seaweedfs/weed/operation"
  17. "github.com/chrislusf/seaweedfs/weed/stats"
  18. "github.com/chrislusf/seaweedfs/weed/util"
  19. _ "github.com/chrislusf/seaweedfs/weed/statik"
  20. "github.com/gorilla/mux"
  21. statik "github.com/rakyll/statik/fs"
  22. )
  23. var serverStats *stats.ServerStats
  24. var startTime = time.Now()
  25. var statikFS http.FileSystem
  26. func init() {
  27. serverStats = stats.NewServerStats()
  28. go serverStats.Start()
  29. statikFS, _ = statik.New()
  30. }
  31. func writeJson(w http.ResponseWriter, r *http.Request, httpStatus int, obj interface{}) (err error) {
  32. var bytes []byte
  33. if r.FormValue("pretty") != "" {
  34. bytes, err = json.MarshalIndent(obj, "", " ")
  35. } else {
  36. bytes, err = json.Marshal(obj)
  37. }
  38. if err != nil {
  39. return
  40. }
  41. callback := r.FormValue("callback")
  42. if callback == "" {
  43. w.Header().Set("Content-Type", "application/json")
  44. w.WriteHeader(httpStatus)
  45. if httpStatus == http.StatusNotModified {
  46. return
  47. }
  48. _, err = w.Write(bytes)
  49. } else {
  50. w.Header().Set("Content-Type", "application/javascript")
  51. w.WriteHeader(httpStatus)
  52. if httpStatus == http.StatusNotModified {
  53. return
  54. }
  55. if _, err = w.Write([]uint8(callback)); err != nil {
  56. return
  57. }
  58. if _, err = w.Write([]uint8("(")); err != nil {
  59. return
  60. }
  61. fmt.Fprint(w, string(bytes))
  62. if _, err = w.Write([]uint8(")")); err != nil {
  63. return
  64. }
  65. }
  66. return
  67. }
  68. // wrapper for writeJson - just logs errors
  69. func writeJsonQuiet(w http.ResponseWriter, r *http.Request, httpStatus int, obj interface{}) {
  70. if err := writeJson(w, r, httpStatus, obj); err != nil {
  71. glog.V(0).Infof("error writing JSON %+v status %d: %v", obj, httpStatus, err)
  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)
  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. Replication: r.FormValue("replication"),
  107. Collection: r.FormValue("collection"),
  108. Ttl: r.FormValue("ttl"),
  109. }
  110. assignResult, ae := operation.Assign(masterUrl, grpcDialOption, ar)
  111. if ae != nil {
  112. writeJsonError(w, r, http.StatusInternalServerError, ae)
  113. return
  114. }
  115. url := "http://" + assignResult.Url + "/" + assignResult.Fid
  116. if lastModified != 0 {
  117. url = url + "?ts=" + strconv.FormatUint(lastModified, 10)
  118. }
  119. debug("upload file to store", url)
  120. uploadResult, err := operation.Upload(url, fname, bytes.NewReader(data), isGzipped, mimeType, pairMap, assignResult.Auth)
  121. if err != nil {
  122. writeJsonError(w, r, http.StatusInternalServerError, err)
  123. return
  124. }
  125. m["fileName"] = fname
  126. m["fid"] = assignResult.Fid
  127. m["fileUrl"] = assignResult.PublicUrl + "/" + assignResult.Fid
  128. m["size"] = originalDataSize
  129. m["eTag"] = uploadResult.ETag
  130. writeJsonQuiet(w, r, http.StatusCreated, m)
  131. return
  132. }
  133. func parseURLPath(path string) (vid, fid, filename, ext string, isVolumeIdOnly bool) {
  134. switch strings.Count(path, "/") {
  135. case 3:
  136. parts := strings.Split(path, "/")
  137. vid, fid, filename = parts[1], parts[2], parts[3]
  138. ext = filepath.Ext(filename)
  139. case 2:
  140. parts := strings.Split(path, "/")
  141. vid, fid = parts[1], parts[2]
  142. dotIndex := strings.LastIndex(fid, ".")
  143. if dotIndex > 0 {
  144. ext = fid[dotIndex:]
  145. fid = fid[0:dotIndex]
  146. }
  147. default:
  148. sepIndex := strings.LastIndex(path, "/")
  149. commaIndex := strings.LastIndex(path[sepIndex:], ",")
  150. if commaIndex <= 0 {
  151. vid, isVolumeIdOnly = path[sepIndex+1:], true
  152. return
  153. }
  154. dotIndex := strings.LastIndex(path[sepIndex:], ".")
  155. vid = path[sepIndex+1 : commaIndex]
  156. fid = path[commaIndex+1:]
  157. ext = ""
  158. if dotIndex > 0 {
  159. fid = path[commaIndex+1 : dotIndex]
  160. ext = path[dotIndex:]
  161. }
  162. }
  163. return
  164. }
  165. func statsHealthHandler(w http.ResponseWriter, r *http.Request) {
  166. m := make(map[string]interface{})
  167. m["Version"] = util.VERSION
  168. writeJsonQuiet(w, r, http.StatusOK, m)
  169. }
  170. func statsCounterHandler(w http.ResponseWriter, r *http.Request) {
  171. m := make(map[string]interface{})
  172. m["Version"] = util.VERSION
  173. m["Counters"] = serverStats
  174. writeJsonQuiet(w, r, http.StatusOK, m)
  175. }
  176. func statsMemoryHandler(w http.ResponseWriter, r *http.Request) {
  177. m := make(map[string]interface{})
  178. m["Version"] = util.VERSION
  179. m["Memory"] = stats.MemStat()
  180. writeJsonQuiet(w, r, http.StatusOK, m)
  181. }
  182. func handleStaticResources(defaultMux *http.ServeMux) {
  183. defaultMux.Handle("/favicon.ico", http.FileServer(statikFS))
  184. defaultMux.Handle("/seaweedfsstatic/", http.StripPrefix("/seaweedfsstatic", http.FileServer(statikFS)))
  185. }
  186. func handleStaticResources2(r *mux.Router) {
  187. r.Handle("/favicon.ico", http.FileServer(statikFS))
  188. r.PathPrefix("/seaweedfsstatic/").Handler(http.StripPrefix("/seaweedfsstatic", http.FileServer(statikFS)))
  189. }