common.go 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  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/security"
  15. "github.com/chrislusf/seaweedfs/weed/stats"
  16. "github.com/chrislusf/seaweedfs/weed/storage"
  17. "github.com/chrislusf/seaweedfs/weed/util"
  18. )
  19. var serverStats *stats.ServerStats
  20. var startTime = time.Now()
  21. func init() {
  22. serverStats = stats.NewServerStats()
  23. go serverStats.Start()
  24. }
  25. func writeJson(w http.ResponseWriter, r *http.Request, httpStatus int, obj interface{}) (err error) {
  26. var bytes []byte
  27. if r.FormValue("pretty") != "" {
  28. bytes, err = json.MarshalIndent(obj, "", " ")
  29. } else {
  30. bytes, err = json.Marshal(obj)
  31. }
  32. if err != nil {
  33. return
  34. }
  35. callback := r.FormValue("callback")
  36. if callback == "" {
  37. w.Header().Set("Content-Type", "application/json")
  38. w.WriteHeader(httpStatus)
  39. _, err = w.Write(bytes)
  40. } else {
  41. w.Header().Set("Content-Type", "application/javascript")
  42. w.WriteHeader(httpStatus)
  43. if _, err = w.Write([]uint8(callback)); err != nil {
  44. return
  45. }
  46. if _, err = w.Write([]uint8("(")); err != nil {
  47. return
  48. }
  49. fmt.Fprint(w, string(bytes))
  50. if _, err = w.Write([]uint8(")")); err != nil {
  51. return
  52. }
  53. }
  54. return
  55. }
  56. // wrapper for writeJson - just logs errors
  57. func writeJsonQuiet(w http.ResponseWriter, r *http.Request, httpStatus int, obj interface{}) {
  58. if err := writeJson(w, r, httpStatus, obj); err != nil {
  59. glog.V(0).Infof("error writing JSON %s: %v", obj, err)
  60. }
  61. }
  62. func writeJsonError(w http.ResponseWriter, r *http.Request, httpStatus int, err error) {
  63. m := make(map[string]interface{})
  64. m["error"] = err.Error()
  65. writeJsonQuiet(w, r, httpStatus, m)
  66. }
  67. func debug(params ...interface{}) {
  68. glog.V(4).Infoln(params...)
  69. }
  70. func submitForClientHandler(w http.ResponseWriter, r *http.Request, masterUrl string) {
  71. jwt := security.GetJwt(r)
  72. m := make(map[string]interface{})
  73. if r.Method != "POST" {
  74. writeJsonError(w, r, http.StatusMethodNotAllowed, errors.New("Only submit via POST!"))
  75. return
  76. }
  77. debug("parsing upload file...")
  78. fname, data, mimeType, pairMap, isGzipped, lastModified, _, _, pe := storage.ParseUpload(r)
  79. if pe != nil {
  80. writeJsonError(w, r, http.StatusBadRequest, pe)
  81. return
  82. }
  83. debug("assigning file id for", fname)
  84. r.ParseForm()
  85. ar := &operation.VolumeAssignRequest{
  86. Count: 1,
  87. Replication: r.FormValue("replication"),
  88. Collection: r.FormValue("collection"),
  89. Ttl: r.FormValue("ttl"),
  90. }
  91. assignResult, ae := operation.Assign(masterUrl, ar)
  92. if ae != nil {
  93. writeJsonError(w, r, http.StatusInternalServerError, ae)
  94. return
  95. }
  96. url := "http://" + assignResult.Url + "/" + assignResult.Fid
  97. if lastModified != 0 {
  98. url = url + "?ts=" + strconv.FormatUint(lastModified, 10)
  99. }
  100. debug("upload file to store", url)
  101. uploadResult, err := operation.Upload(url, fname, bytes.NewReader(data), isGzipped, mimeType, pairMap, jwt)
  102. if err != nil {
  103. writeJsonError(w, r, http.StatusInternalServerError, err)
  104. return
  105. }
  106. m["fileName"] = fname
  107. m["fid"] = assignResult.Fid
  108. m["fileUrl"] = assignResult.PublicUrl + "/" + assignResult.Fid
  109. m["size"] = uploadResult.Size
  110. writeJsonQuiet(w, r, http.StatusCreated, m)
  111. return
  112. }
  113. func deleteForClientHandler(w http.ResponseWriter, r *http.Request, masterUrl string) {
  114. r.ParseForm()
  115. fids := r.Form["fid"]
  116. ret, err := operation.DeleteFiles(masterUrl, fids)
  117. if err != nil {
  118. writeJsonError(w, r, http.StatusInternalServerError, err)
  119. return
  120. }
  121. writeJsonQuiet(w, r, http.StatusAccepted, ret)
  122. }
  123. func parseURLPath(path string) (vid, fid, filename, ext string, isVolumeIdOnly bool) {
  124. switch strings.Count(path, "/") {
  125. case 3:
  126. parts := strings.Split(path, "/")
  127. vid, fid, filename = parts[1], parts[2], parts[3]
  128. ext = filepath.Ext(filename)
  129. case 2:
  130. parts := strings.Split(path, "/")
  131. vid, fid = parts[1], parts[2]
  132. dotIndex := strings.LastIndex(fid, ".")
  133. if dotIndex > 0 {
  134. ext = fid[dotIndex:]
  135. fid = fid[0:dotIndex]
  136. }
  137. default:
  138. sepIndex := strings.LastIndex(path, "/")
  139. commaIndex := strings.LastIndex(path[sepIndex:], ",")
  140. if commaIndex <= 0 {
  141. vid, isVolumeIdOnly = path[sepIndex+1:], true
  142. return
  143. }
  144. dotIndex := strings.LastIndex(path[sepIndex:], ".")
  145. vid = path[sepIndex+1 : commaIndex]
  146. fid = path[commaIndex+1:]
  147. ext = ""
  148. if dotIndex > 0 {
  149. fid = path[commaIndex+1 : dotIndex]
  150. ext = path[dotIndex:]
  151. }
  152. }
  153. return
  154. }
  155. func statsHealthHandler(w http.ResponseWriter, r *http.Request) {
  156. m := make(map[string]interface{})
  157. m["Version"] = util.VERSION
  158. writeJsonQuiet(w, r, http.StatusOK, m)
  159. }
  160. func statsCounterHandler(w http.ResponseWriter, r *http.Request) {
  161. m := make(map[string]interface{})
  162. m["Version"] = util.VERSION
  163. m["Counters"] = serverStats
  164. writeJsonQuiet(w, r, http.StatusOK, m)
  165. }
  166. func statsMemoryHandler(w http.ResponseWriter, r *http.Request) {
  167. m := make(map[string]interface{})
  168. m["Version"] = util.VERSION
  169. m["Memory"] = stats.MemStat()
  170. writeJsonQuiet(w, r, http.StatusOK, m)
  171. }