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.

268 lines
7.3 KiB

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