seaweedfs/weed/server/volume_server_handlers_read.go

260 lines
7.1 KiB
Go
Raw Normal View History

package weed_server
import (
2015-12-15 14:38:58 +08:00
"bytes"
"encoding/json"
2019-06-06 15:29:02 +08:00
"errors"
"fmt"
"io"
"mime"
"net/http"
2016-06-14 06:07:17 +08:00
"net/url"
2015-12-15 14:38:58 +08:00
"path"
"strconv"
"strings"
"time"
"github.com/chrislusf/seaweedfs/weed/glog"
"github.com/chrislusf/seaweedfs/weed/images"
"github.com/chrislusf/seaweedfs/weed/operation"
2019-06-16 03:21:44 +08:00
"github.com/chrislusf/seaweedfs/weed/stats"
2019-04-19 12:43:36 +08:00
"github.com/chrislusf/seaweedfs/weed/storage/needle"
"github.com/chrislusf/seaweedfs/weed/util"
)
var fileNameEscaper = strings.NewReplacer("\\", "\\\\", "\"", "\\\"")
func (vs *VolumeServer) GetOrHeadHandler(w http.ResponseWriter, r *http.Request) {
2019-06-14 15:54:56 +08:00
2019-06-16 03:21:44 +08:00
stats.VolumeServerRequestCounter.WithLabelValues("get").Inc()
2019-06-14 15:54:56 +08:00
start := time.Now()
2019-06-16 03:21:44 +08:00
defer func() { stats.VolumeServerRequestHistogram.WithLabelValues("get").Observe(time.Since(start).Seconds()) }()
2019-06-14 15:54:56 +08:00
2019-04-19 12:43:36 +08:00
n := new(needle.Needle)
vid, fid, filename, ext, _ := parseURLPath(r.URL.Path)
2019-06-06 15:29:02 +08:00
if !vs.maybeCheckJwtAuthorization(r, vid, fid, false) {
writeJsonError(w, r, http.StatusUnauthorized, errors.New("wrong jwt"))
return
}
2019-04-19 12:43:36 +08:00
volumeId, err := needle.NewVolumeId(vid)
if err != nil {
glog.V(2).Infoln("parsing error:", err, r.URL.Path)
w.WriteHeader(http.StatusBadRequest)
return
}
err = n.ParsePath(fid)
if err != nil {
glog.V(2).Infoln("parsing fid error:", err, r.URL.Path)
w.WriteHeader(http.StatusBadRequest)
return
}
2020-01-25 09:26:03 +08:00
// glog.V(4).Infoln("volume", volumeId, "reading", n)
hasVolume := vs.store.HasVolume(volumeId)
2019-05-28 12:40:51 +08:00
_, hasEcVolume := vs.store.FindEcVolume(volumeId)
if !hasVolume && !hasEcVolume {
if !vs.ReadRedirect {
glog.V(2).Infoln("volume is not local:", err, r.URL.Path)
w.WriteHeader(http.StatusNotFound)
return
}
lookupResult, err := operation.Lookup(vs.GetMaster(), volumeId.String())
glog.V(2).Infoln("volume", volumeId, "found on", lookupResult, "error", err)
if err == nil && len(lookupResult.Locations) > 0 {
u, _ := url.Parse(util.NormalizeUrl(lookupResult.Locations[0].PublicUrl))
u.Path = fmt.Sprintf("%s/%s,%s", u.Path, vid, fid)
arg := url.Values{}
if c := r.FormValue("collection"); c != "" {
arg.Set("collection", c)
}
u.RawQuery = arg.Encode()
http.Redirect(w, r, u.String(), http.StatusMovedPermanently)
} else {
glog.V(2).Infoln("lookup error:", err, r.URL.Path)
w.WriteHeader(http.StatusNotFound)
}
return
}
cookie := n.Cookie
var count int
if hasVolume {
count, err = vs.store.ReadVolumeNeedle(volumeId, n)
2019-05-28 12:40:51 +08:00
} else if hasEcVolume {
count, err = vs.store.ReadEcShardNeedle(volumeId, n)
}
2020-01-25 09:26:03 +08:00
// glog.V(4).Infoln("read bytes", count, "error", err)
if err != nil || count < 0 {
2019-06-06 14:20:26 +08:00
glog.V(0).Infof("read %s isNormalVolume %v error: %v", r.URL.Path, hasVolume, err)
w.WriteHeader(http.StatusNotFound)
return
}
if n.Cookie != cookie {
2018-11-22 16:42:56 +08:00
glog.V(0).Infof("request %s with cookie:%x expected:%x from %s agent %s", r.URL.Path, cookie, n.Cookie, r.RemoteAddr, r.UserAgent())
w.WriteHeader(http.StatusNotFound)
return
}
if n.LastModified != 0 {
w.Header().Set("Last-Modified", time.Unix(int64(n.LastModified), 0).UTC().Format(http.TimeFormat))
if r.Header.Get("If-Modified-Since") != "" {
if t, parseError := time.Parse(http.TimeFormat, r.Header.Get("If-Modified-Since")); parseError == nil {
if t.Unix() >= int64(n.LastModified) {
w.WriteHeader(http.StatusNotModified)
return
}
}
}
}
2018-09-10 07:25:43 +08:00
if inm := r.Header.Get("If-None-Match"); inm == "\""+n.Etag()+"\"" {
w.WriteHeader(http.StatusNotModified)
return
}
if r.Header.Get("ETag-MD5") == "True" {
setEtag(w, n.MD5())
2018-11-23 16:26:15 +08:00
} else {
setEtag(w, n.Etag())
}
if n.HasPairs() {
pairMap := make(map[string]string)
err = json.Unmarshal(n.Pairs, &pairMap)
if err != nil {
glog.V(0).Infoln("Unmarshal pairs error:", err)
}
for k, v := range pairMap {
w.Header().Set(k, v)
}
}
if vs.tryHandleChunkedFile(n, filename, w, r) {
return
}
if n.NameSize > 0 && filename == "" {
filename = string(n.Name)
if ext == "" {
ext = path.Ext(filename)
}
}
mtype := ""
if n.MimeSize > 0 {
mt := string(n.Mime)
if !strings.HasPrefix(mt, "application/octet-stream") {
mtype = mt
}
}
if ext != ".gz" {
if n.IsGzipped() {
if strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
w.Header().Set("Content-Encoding", "gzip")
} else {
2019-04-19 12:43:36 +08:00
if n.Data, err = util.UnGzipData(n.Data); err != nil {
glog.V(0).Infoln("ungzip error:", err, r.URL.Path)
}
}
}
}
2018-07-24 15:58:52 +08:00
2018-07-24 16:09:32 +08:00
rs := conditionallyResizeImages(bytes.NewReader(n.Data), ext, r)
if e := writeResponseContent(filename, mtype, rs, w, r); e != nil {
glog.V(2).Infoln("response write error:", e)
}
}
2019-04-19 12:43:36 +08:00
func (vs *VolumeServer) tryHandleChunkedFile(n *needle.Needle, fileName string, w http.ResponseWriter, r *http.Request) (processed bool) {
if !n.IsChunkedManifest() || r.URL.Query().Get("cm") == "false" {
return false
}
chunkManifest, e := operation.LoadChunkManifest(n.Data, n.IsGzipped())
if e != nil {
2015-12-15 14:38:58 +08:00
glog.V(0).Infof("load chunked manifest (%s) error: %v", r.URL.Path, e)
return false
}
if fileName == "" && chunkManifest.Name != "" {
fileName = chunkManifest.Name
}
ext := path.Ext(fileName)
mType := ""
if chunkManifest.Mime != "" {
mt := chunkManifest.Mime
if !strings.HasPrefix(mt, "application/octet-stream") {
mType = mt
}
}
w.Header().Set("X-File-Store", "chunked")
2015-12-02 15:00:46 +08:00
chunkedFileReader := &operation.ChunkedFileReader{
Manifest: chunkManifest,
Master: vs.GetMaster(),
}
defer chunkedFileReader.Close()
2018-07-24 15:58:52 +08:00
rs := conditionallyResizeImages(chunkedFileReader, ext, r)
if e := writeResponseContent(fileName, mType, rs, w, r); e != nil {
glog.V(2).Infoln("response write error:", e)
}
return true
}
func conditionallyResizeImages(originalDataReaderSeeker io.ReadSeeker, ext string, r *http.Request) io.ReadSeeker {
rs := originalDataReaderSeeker
if len(ext) > 0 {
ext = strings.ToLower(ext)
}
if ext == ".png" || ext == ".jpg" || ext == ".jpeg" || ext == ".gif" {
width, height := 0, 0
if r.FormValue("width") != "" {
width, _ = strconv.Atoi(r.FormValue("width"))
}
if r.FormValue("height") != "" {
height, _ = strconv.Atoi(r.FormValue("height"))
}
2018-07-24 15:58:52 +08:00
rs, _, _ = images.Resized(ext, originalDataReaderSeeker, width, height, r.FormValue("mode"))
}
2018-07-24 15:58:52 +08:00
return rs
}
func writeResponseContent(filename, mimeType string, rs io.ReadSeeker, w http.ResponseWriter, r *http.Request) error {
totalSize, e := rs.Seek(0, 2)
if mimeType == "" {
if ext := path.Ext(filename); ext != "" {
mimeType = mime.TypeByExtension(ext)
}
}
if mimeType != "" {
w.Header().Set("Content-Type", mimeType)
}
if filename != "" {
contentDisposition := "inline"
if r.FormValue("dl") != "" {
if dl, _ := strconv.ParseBool(r.FormValue("dl")); dl {
contentDisposition = "attachment"
}
}
w.Header().Set("Content-Disposition", contentDisposition+`; filename="`+fileNameEscaper.Replace(filename)+`"`)
}
w.Header().Set("Accept-Ranges", "bytes")
if r.Method == "HEAD" {
w.Header().Set("Content-Length", strconv.FormatInt(totalSize, 10))
return nil
}
2020-03-08 10:06:48 +08:00
processRangeRequst(r, w, totalSize, mimeType, func(writer io.Writer, offset int64, size int64) error {
if _, e = rs.Seek(offset, 0); e != nil {
return e
}
2020-03-08 10:06:48 +08:00
_, e = io.CopyN(writer, rs, size)
return e
2020-03-08 10:06:48 +08:00
})
return nil
}