common.go 5.6 KB

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