common.go 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. package weed_server
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "io/fs"
  9. "mime/multipart"
  10. "net/http"
  11. "path/filepath"
  12. "strconv"
  13. "strings"
  14. "time"
  15. "google.golang.org/grpc"
  16. "github.com/chrislusf/seaweedfs/weed/glog"
  17. "github.com/chrislusf/seaweedfs/weed/operation"
  18. "github.com/chrislusf/seaweedfs/weed/stats"
  19. "github.com/chrislusf/seaweedfs/weed/storage/needle"
  20. "github.com/chrislusf/seaweedfs/weed/util"
  21. "github.com/gorilla/mux"
  22. )
  23. var serverStats *stats.ServerStats
  24. var startTime = time.Now()
  25. func init() {
  26. serverStats = stats.NewServerStats()
  27. go serverStats.Start()
  28. }
  29. func writeJson(w http.ResponseWriter, r *http.Request, httpStatus int, obj interface{}) (err error) {
  30. var bytes []byte
  31. if obj != nil {
  32. if r.FormValue("pretty") != "" {
  33. bytes, err = json.MarshalIndent(obj, "", " ")
  34. } else {
  35. bytes, err = json.Marshal(obj)
  36. }
  37. }
  38. if err != nil {
  39. return
  40. }
  41. if httpStatus >= 400 {
  42. glog.V(0).Infof("response method:%s URL:%s with httpStatus:%d and JSON:%s",
  43. r.Method, r.URL.String(), httpStatus, string(bytes))
  44. }
  45. callback := r.FormValue("callback")
  46. if callback == "" {
  47. w.Header().Set("Content-Type", "application/json")
  48. w.WriteHeader(httpStatus)
  49. if httpStatus == http.StatusNotModified {
  50. return
  51. }
  52. _, err = w.Write(bytes)
  53. } else {
  54. w.Header().Set("Content-Type", "application/javascript")
  55. w.WriteHeader(httpStatus)
  56. if httpStatus == http.StatusNotModified {
  57. return
  58. }
  59. if _, err = w.Write([]uint8(callback)); err != nil {
  60. return
  61. }
  62. if _, err = w.Write([]uint8("(")); err != nil {
  63. return
  64. }
  65. fmt.Fprint(w, string(bytes))
  66. if _, err = w.Write([]uint8(")")); err != nil {
  67. return
  68. }
  69. }
  70. return
  71. }
  72. // wrapper for writeJson - just logs errors
  73. func writeJsonQuiet(w http.ResponseWriter, r *http.Request, httpStatus int, obj interface{}) {
  74. if err := writeJson(w, r, httpStatus, obj); err != nil {
  75. glog.V(0).Infof("error writing JSON status %d: %v", httpStatus, err)
  76. glog.V(1).Infof("JSON content: %+v", obj)
  77. }
  78. }
  79. func writeJsonError(w http.ResponseWriter, r *http.Request, httpStatus int, err error) {
  80. m := make(map[string]interface{})
  81. m["error"] = err.Error()
  82. writeJsonQuiet(w, r, httpStatus, m)
  83. }
  84. func debug(params ...interface{}) {
  85. glog.V(4).Infoln(params...)
  86. }
  87. func submitForClientHandler(w http.ResponseWriter, r *http.Request, masterFn operation.GetMasterFn, grpcDialOption grpc.DialOption) {
  88. m := make(map[string]interface{})
  89. if r.Method != "POST" {
  90. writeJsonError(w, r, http.StatusMethodNotAllowed, errors.New("Only submit via POST!"))
  91. return
  92. }
  93. debug("parsing upload file...")
  94. bytesBuffer := bufPool.Get().(*bytes.Buffer)
  95. defer bufPool.Put(bytesBuffer)
  96. pu, pe := needle.ParseUpload(r, 256*1024*1024, bytesBuffer)
  97. if pe != nil {
  98. writeJsonError(w, r, http.StatusBadRequest, pe)
  99. return
  100. }
  101. debug("assigning file id for", pu.FileName)
  102. r.ParseForm()
  103. count := uint64(1)
  104. if r.FormValue("count") != "" {
  105. count, pe = strconv.ParseUint(r.FormValue("count"), 10, 32)
  106. if pe != nil {
  107. writeJsonError(w, r, http.StatusBadRequest, pe)
  108. return
  109. }
  110. }
  111. ar := &operation.VolumeAssignRequest{
  112. Count: count,
  113. DataCenter: r.FormValue("dataCenter"),
  114. Rack: r.FormValue("rack"),
  115. Replication: r.FormValue("replication"),
  116. Collection: r.FormValue("collection"),
  117. Ttl: r.FormValue("ttl"),
  118. DiskType: r.FormValue("disk"),
  119. }
  120. assignResult, ae := operation.Assign(masterFn, grpcDialOption, ar)
  121. if ae != nil {
  122. writeJsonError(w, r, http.StatusInternalServerError, ae)
  123. return
  124. }
  125. url := "http://" + assignResult.Url + "/" + assignResult.Fid
  126. if pu.ModifiedTime != 0 {
  127. url = url + "?ts=" + strconv.FormatUint(pu.ModifiedTime, 10)
  128. }
  129. debug("upload file to store", url)
  130. uploadResult, err := operation.UploadData(url, pu.FileName, false, pu.Data, pu.IsGzipped, pu.MimeType, pu.PairMap, assignResult.Auth)
  131. if err != nil {
  132. writeJsonError(w, r, http.StatusInternalServerError, err)
  133. return
  134. }
  135. m["fileName"] = pu.FileName
  136. m["fid"] = assignResult.Fid
  137. m["fileUrl"] = assignResult.PublicUrl + "/" + assignResult.Fid
  138. m["size"] = pu.OriginalDataSize
  139. m["eTag"] = uploadResult.ETag
  140. writeJsonQuiet(w, r, http.StatusCreated, m)
  141. return
  142. }
  143. func parseURLPath(path string) (vid, fid, filename, ext string, isVolumeIdOnly bool) {
  144. switch strings.Count(path, "/") {
  145. case 3:
  146. parts := strings.Split(path, "/")
  147. vid, fid, filename = parts[1], parts[2], parts[3]
  148. ext = filepath.Ext(filename)
  149. case 2:
  150. parts := strings.Split(path, "/")
  151. vid, fid = parts[1], parts[2]
  152. dotIndex := strings.LastIndex(fid, ".")
  153. if dotIndex > 0 {
  154. ext = fid[dotIndex:]
  155. fid = fid[0:dotIndex]
  156. }
  157. default:
  158. sepIndex := strings.LastIndex(path, "/")
  159. commaIndex := strings.LastIndex(path[sepIndex:], ",")
  160. if commaIndex <= 0 {
  161. vid, isVolumeIdOnly = path[sepIndex+1:], true
  162. return
  163. }
  164. dotIndex := strings.LastIndex(path[sepIndex:], ".")
  165. vid = path[sepIndex+1 : commaIndex]
  166. fid = path[commaIndex+1:]
  167. ext = ""
  168. if dotIndex > 0 {
  169. fid = path[commaIndex+1 : dotIndex]
  170. ext = path[dotIndex:]
  171. }
  172. }
  173. return
  174. }
  175. func statsHealthHandler(w http.ResponseWriter, r *http.Request) {
  176. m := make(map[string]interface{})
  177. m["Version"] = util.Version()
  178. writeJsonQuiet(w, r, http.StatusOK, m)
  179. }
  180. func statsCounterHandler(w http.ResponseWriter, r *http.Request) {
  181. m := make(map[string]interface{})
  182. m["Version"] = util.Version()
  183. m["Counters"] = serverStats
  184. writeJsonQuiet(w, r, http.StatusOK, m)
  185. }
  186. func statsMemoryHandler(w http.ResponseWriter, r *http.Request) {
  187. m := make(map[string]interface{})
  188. m["Version"] = util.Version()
  189. m["Memory"] = stats.MemStat()
  190. writeJsonQuiet(w, r, http.StatusOK, m)
  191. }
  192. var StaticFS fs.FS
  193. func handleStaticResources(defaultMux *http.ServeMux) {
  194. defaultMux.Handle("/favicon.ico", http.FileServer(http.FS(StaticFS)))
  195. defaultMux.Handle("/seaweedfsstatic/", http.StripPrefix("/seaweedfsstatic", http.FileServer(http.FS(StaticFS))))
  196. }
  197. func handleStaticResources2(r *mux.Router) {
  198. r.Handle("/favicon.ico", http.FileServer(http.FS(StaticFS)))
  199. r.PathPrefix("/seaweedfsstatic/").Handler(http.StripPrefix("/seaweedfsstatic", http.FileServer(http.FS(StaticFS))))
  200. }
  201. func adjustHeaderContentDisposition(w http.ResponseWriter, r *http.Request, filename string) {
  202. if filename != "" {
  203. contentDisposition := "inline"
  204. if r.FormValue("dl") != "" {
  205. if dl, _ := strconv.ParseBool(r.FormValue("dl")); dl {
  206. contentDisposition = "attachment"
  207. }
  208. }
  209. w.Header().Set("Content-Disposition", contentDisposition+`; filename="`+fileNameEscaper.Replace(filename)+`"`)
  210. }
  211. }
  212. func processRangeRequest(r *http.Request, w http.ResponseWriter, totalSize int64, mimeType string, writeFn func(writer io.Writer, offset int64, size int64) error) {
  213. rangeReq := r.Header.Get("Range")
  214. if rangeReq == "" {
  215. w.Header().Set("Content-Length", strconv.FormatInt(totalSize, 10))
  216. if err := writeFn(w, 0, totalSize); err != nil {
  217. http.Error(w, err.Error(), http.StatusInternalServerError)
  218. return
  219. }
  220. return
  221. }
  222. //the rest is dealing with partial content request
  223. //mostly copy from src/pkg/net/http/fs.go
  224. ranges, err := parseRange(rangeReq, totalSize)
  225. if err != nil {
  226. http.Error(w, err.Error(), http.StatusRequestedRangeNotSatisfiable)
  227. return
  228. }
  229. if sumRangesSize(ranges) > totalSize {
  230. // The total number of bytes in all the ranges
  231. // is larger than the size of the file by
  232. // itself, so this is probably an attack, or a
  233. // dumb client. Ignore the range request.
  234. return
  235. }
  236. if len(ranges) == 0 {
  237. return
  238. }
  239. if len(ranges) == 1 {
  240. // RFC 2616, Section 14.16:
  241. // "When an HTTP message includes the content of a single
  242. // range (for example, a response to a request for a
  243. // single range, or to a request for a set of ranges
  244. // that overlap without any holes), this content is
  245. // transmitted with a Content-Range header, and a
  246. // Content-Length header showing the number of bytes
  247. // actually transferred.
  248. // ...
  249. // A response to a request for a single range MUST NOT
  250. // be sent using the multipart/byteranges media type."
  251. ra := ranges[0]
  252. w.Header().Set("Content-Length", strconv.FormatInt(ra.length, 10))
  253. w.Header().Set("Content-Range", ra.contentRange(totalSize))
  254. w.WriteHeader(http.StatusPartialContent)
  255. err = writeFn(w, ra.start, ra.length)
  256. if err != nil {
  257. http.Error(w, err.Error(), http.StatusInternalServerError)
  258. return
  259. }
  260. return
  261. }
  262. // process multiple ranges
  263. for _, ra := range ranges {
  264. if ra.start > totalSize {
  265. http.Error(w, "Out of Range", http.StatusRequestedRangeNotSatisfiable)
  266. return
  267. }
  268. }
  269. sendSize := rangesMIMESize(ranges, mimeType, totalSize)
  270. pr, pw := io.Pipe()
  271. mw := multipart.NewWriter(pw)
  272. w.Header().Set("Content-Type", "multipart/byteranges; boundary="+mw.Boundary())
  273. sendContent := pr
  274. defer pr.Close() // cause writing goroutine to fail and exit if CopyN doesn't finish.
  275. go func() {
  276. for _, ra := range ranges {
  277. part, e := mw.CreatePart(ra.mimeHeader(mimeType, totalSize))
  278. if e != nil {
  279. pw.CloseWithError(e)
  280. return
  281. }
  282. if e = writeFn(part, ra.start, ra.length); e != nil {
  283. pw.CloseWithError(e)
  284. return
  285. }
  286. }
  287. mw.Close()
  288. pw.Close()
  289. }()
  290. if w.Header().Get("Content-Encoding") == "" {
  291. w.Header().Set("Content-Length", strconv.FormatInt(sendSize, 10))
  292. }
  293. w.WriteHeader(http.StatusPartialContent)
  294. if _, err := io.CopyN(w, sendContent, sendSize); err != nil {
  295. http.Error(w, "Internal Error", http.StatusInternalServerError)
  296. return
  297. }
  298. }