diff options
Diffstat (limited to 'weed/server')
| -rw-r--r-- | weed/server/common.go | 88 | ||||
| -rw-r--r-- | weed/server/filer_server_handlers_read.go | 6 | ||||
| -rw-r--r-- | weed/server/filer_server_handlers_read_dir.go | 2 | ||||
| -rw-r--r-- | weed/server/filer_server_handlers_write.go | 20 | ||||
| -rw-r--r-- | weed/server/filer_server_handlers_write_autochunk.go | 4 | ||||
| -rw-r--r-- | weed/server/master_server.go | 26 | ||||
| -rw-r--r-- | weed/server/master_server_handlers.go | 12 | ||||
| -rw-r--r-- | weed/server/master_server_handlers_admin.go | 20 | ||||
| -rw-r--r-- | weed/server/raft_server_handlers.go | 2 | ||||
| -rw-r--r-- | weed/server/volume_server.go | 12 | ||||
| -rw-r--r-- | weed/server/volume_server_fasthttp_handlers.go | 81 | ||||
| -rw-r--r-- | weed/server/volume_server_fasthttp_handlers_read.go | 366 | ||||
| -rw-r--r-- | weed/server/volume_server_fasthttp_handlers_write.go | 156 | ||||
| -rw-r--r-- | weed/server/volume_server_handlers.go | 18 | ||||
| -rw-r--r-- | weed/server/volume_server_handlers_admin.go | 4 | ||||
| -rw-r--r-- | weed/server/volume_server_handlers_read.go | 10 | ||||
| -rw-r--r-- | weed/server/volume_server_handlers_write.go | 48 |
17 files changed, 767 insertions, 108 deletions
diff --git a/weed/server/common.go b/weed/server/common.go index 31a9a73b8..8a1ccdddc 100644 --- a/weed/server/common.go +++ b/weed/server/common.go @@ -11,6 +11,7 @@ import ( "strings" "time" + "github.com/valyala/fasthttp" "google.golang.org/grpc" "github.com/chrislusf/seaweedfs/weed/glog" @@ -35,7 +36,47 @@ func init() { statikFS, _ = statik.New() } -func writeJson(w http.ResponseWriter, r *http.Request, httpStatus int, obj interface{}) (err error) { + +func writeJson(ctx *fasthttp.RequestCtx, httpStatus int, obj interface{}) (err error) { + var bytes []byte + if ctx.FormValue("pretty") != nil { + bytes, err = json.MarshalIndent(obj, "", " ") + } else { + bytes, err = json.Marshal(obj) + } + if err != nil { + return + } + callback := ctx.FormValue("callback") + if callback == nil { + ctx.Response.Header.Set("Content-Type", "application/json") + ctx.SetStatusCode(httpStatus) + if httpStatus == http.StatusNotModified { + return + } + _, err = ctx.Response.BodyWriter().Write(bytes) + } else { + ctx.Response.Header.Set("Content-Type", "application/javascript") + ctx.SetStatusCode(httpStatus) + if httpStatus == http.StatusNotModified { + return + } + if _, err = ctx.Response.BodyWriter().Write([]uint8(callback)); err != nil { + return + } + if _, err = ctx.Response.BodyWriter().Write([]uint8("(")); err != nil { + return + } + fmt.Fprint(ctx.Response.BodyWriter(), string(bytes)) + if _, err = ctx.Response.BodyWriter().Write([]uint8(")")); err != nil { + return + } + } + + return +} + +func oldWriteJson(w http.ResponseWriter, r *http.Request, httpStatus int, obj interface{}) (err error) { var bytes []byte if r.FormValue("pretty") != "" { bytes, err = json.MarshalIndent(obj, "", " ") @@ -74,17 +115,32 @@ func writeJson(w http.ResponseWriter, r *http.Request, httpStatus int, obj inter return } -// wrapper for writeJson - just logs errors -func writeJsonQuiet(w http.ResponseWriter, r *http.Request, httpStatus int, obj interface{}) { - if err := writeJson(w, r, httpStatus, obj); err != nil { +// wrapper for oldWriteJson - just logs errors +func oldWriteJsonQuiet(w http.ResponseWriter, r *http.Request, httpStatus int, obj interface{}) { + if err := oldWriteJson(w, r, httpStatus, obj); err != nil { + glog.V(0).Infof("error writing JSON status %d: %v", httpStatus, err) + glog.V(1).Infof("JSON content: %+v", obj) + } +} + +// wrapper for oldWriteJson - just logs errors +func writeJsonQuiet(ctx *fasthttp.RequestCtx, httpStatus int, obj interface{}) { + if err := writeJson(ctx, httpStatus, obj); err != nil { glog.V(0).Infof("error writing JSON status %d: %v", httpStatus, err) glog.V(1).Infof("JSON content: %+v", obj) } } -func writeJsonError(w http.ResponseWriter, r *http.Request, httpStatus int, err error) { + +func oldWriteJsonError(w http.ResponseWriter, r *http.Request, httpStatus int, err error) { + m := make(map[string]interface{}) + m["error"] = err.Error() + oldWriteJsonQuiet(w, r, httpStatus, m) +} + +func writeJsonError(ctx *fasthttp.RequestCtx, httpStatus int, err error) { m := make(map[string]interface{}) m["error"] = err.Error() - writeJsonQuiet(w, r, httpStatus, m) + writeJsonQuiet(ctx, httpStatus, m) } func debug(params ...interface{}) { @@ -94,14 +150,14 @@ func debug(params ...interface{}) { func submitForClientHandler(w http.ResponseWriter, r *http.Request, masterUrl string, grpcDialOption grpc.DialOption) { m := make(map[string]interface{}) if r.Method != "POST" { - writeJsonError(w, r, http.StatusMethodNotAllowed, errors.New("Only submit via POST!")) + oldWriteJsonError(w, r, http.StatusMethodNotAllowed, errors.New("Only submit via POST!")) return } debug("parsing upload file...") - fname, data, mimeType, pairMap, isGzipped, originalDataSize, lastModified, _, _, pe := needle.ParseUpload(r, 256*1024*1024) + fname, data, mimeType, pairMap, isGzipped, originalDataSize, lastModified, _, _, pe := needle.OldParseUpload(r, 256*1024*1024) if pe != nil { - writeJsonError(w, r, http.StatusBadRequest, pe) + oldWriteJsonError(w, r, http.StatusBadRequest, pe) return } @@ -111,7 +167,7 @@ func submitForClientHandler(w http.ResponseWriter, r *http.Request, masterUrl st if r.FormValue("count") != "" { count, pe = strconv.ParseUint(r.FormValue("count"), 10, 32) if pe != nil { - writeJsonError(w, r, http.StatusBadRequest, pe) + oldWriteJsonError(w, r, http.StatusBadRequest, pe) return } } @@ -124,7 +180,7 @@ func submitForClientHandler(w http.ResponseWriter, r *http.Request, masterUrl st } assignResult, ae := operation.Assign(masterUrl, grpcDialOption, ar) if ae != nil { - writeJsonError(w, r, http.StatusInternalServerError, ae) + oldWriteJsonError(w, r, http.StatusInternalServerError, ae) return } @@ -136,7 +192,7 @@ func submitForClientHandler(w http.ResponseWriter, r *http.Request, masterUrl st debug("upload file to store", url) uploadResult, err := operation.Upload(url, fname, bytes.NewReader(data), isGzipped, mimeType, pairMap, assignResult.Auth) if err != nil { - writeJsonError(w, r, http.StatusInternalServerError, err) + oldWriteJsonError(w, r, http.StatusInternalServerError, err) return } @@ -145,7 +201,7 @@ func submitForClientHandler(w http.ResponseWriter, r *http.Request, masterUrl st m["fileUrl"] = assignResult.PublicUrl + "/" + assignResult.Fid m["size"] = originalDataSize m["eTag"] = uploadResult.ETag - writeJsonQuiet(w, r, http.StatusCreated, m) + oldWriteJsonQuiet(w, r, http.StatusCreated, m) return } @@ -185,20 +241,20 @@ func parseURLPath(path string) (vid, fid, filename, ext string, isVolumeIdOnly b func statsHealthHandler(w http.ResponseWriter, r *http.Request) { m := make(map[string]interface{}) m["Version"] = util.VERSION - writeJsonQuiet(w, r, http.StatusOK, m) + oldWriteJsonQuiet(w, r, http.StatusOK, m) } func statsCounterHandler(w http.ResponseWriter, r *http.Request) { m := make(map[string]interface{}) m["Version"] = util.VERSION m["Counters"] = serverStats - writeJsonQuiet(w, r, http.StatusOK, m) + oldWriteJsonQuiet(w, r, http.StatusOK, m) } func statsMemoryHandler(w http.ResponseWriter, r *http.Request) { m := make(map[string]interface{}) m["Version"] = util.VERSION m["Memory"] = stats.MemStat() - writeJsonQuiet(w, r, http.StatusOK, m) + oldWriteJsonQuiet(w, r, http.StatusOK, m) } func handleStaticResources(defaultMux *http.ServeMux) { diff --git a/weed/server/filer_server_handlers_read.go b/weed/server/filer_server_handlers_read.go index ba21298ba..771cda959 100644 --- a/weed/server/filer_server_handlers_read.go +++ b/weed/server/filer_server_handlers_read.go @@ -69,7 +69,7 @@ func (fs *FilerServer) GetOrHeadHandler(w http.ResponseWriter, r *http.Request, if r.Method == "HEAD" { w.Header().Set("Content-Length", strconv.FormatInt(int64(filer2.TotalSize(entry.Chunks)), 10)) w.Header().Set("Last-Modified", entry.Attr.Mtime.Format(http.TimeFormat)) - setEtag(w, filer2.ETag(entry.Chunks)) + oldSetEtag(w, filer2.ETag(entry.Chunks)) return } @@ -122,7 +122,7 @@ func (fs *FilerServer) handleSingleChunk(w http.ResponseWriter, r *http.Request, resp, do_err := util.Do(request) if do_err != nil { glog.V(0).Infoln("failing to connect to volume server", do_err.Error()) - writeJsonError(w, r, http.StatusInternalServerError, do_err) + oldWriteJsonError(w, r, http.StatusInternalServerError, do_err) return } defer func() { @@ -150,7 +150,7 @@ func (fs *FilerServer) handleMultipleChunks(w http.ResponseWriter, r *http.Reque if mimeType != "" { w.Header().Set("Content-Type", mimeType) } - setEtag(w, filer2.ETag(entry.Chunks)) + oldSetEtag(w, filer2.ETag(entry.Chunks)) totalSize := int64(filer2.TotalSize(entry.Chunks)) diff --git a/weed/server/filer_server_handlers_read_dir.go b/weed/server/filer_server_handlers_read_dir.go index 87e864559..852c7637b 100644 --- a/weed/server/filer_server_handlers_read_dir.go +++ b/weed/server/filer_server_handlers_read_dir.go @@ -52,7 +52,7 @@ func (fs *FilerServer) listDirectoryHandler(w http.ResponseWriter, r *http.Reque glog.V(4).Infof("listDirectory %s, last file %s, limit %d: %d items", path, lastFileName, limit, len(entries)) if r.Header.Get("Accept") == "application/json" { - writeJsonQuiet(w, r, http.StatusOK, struct { + oldWriteJsonQuiet(w, r, http.StatusOK, struct { Path string Entries interface{} Limit int diff --git a/weed/server/filer_server_handlers_write.go b/weed/server/filer_server_handlers_write.go index 4707f1011..4772d2880 100644 --- a/weed/server/filer_server_handlers_write.go +++ b/weed/server/filer_server_handlers_write.go @@ -65,7 +65,7 @@ func (fs *FilerServer) assignNewFileInfo(w http.ResponseWriter, r *http.Request, assignResult, ae := operation.Assign(fs.filer.GetMaster(), fs.grpcDialOption, ar, altRequest) if ae != nil { glog.Errorf("failing to assign a file id: %v", ae) - writeJsonError(w, r, http.StatusInternalServerError, ae) + oldWriteJsonError(w, r, http.StatusInternalServerError, ae) err = ae return } @@ -135,8 +135,8 @@ func (fs *FilerServer) PostHandler(w http.ResponseWriter, r *http.Request) { Fid: fileId, Url: urlLocation, } - setEtag(w, ret.ETag) - writeJsonQuiet(w, r, http.StatusCreated, reply) + oldSetEtag(w, ret.ETag) + oldWriteJsonQuiet(w, r, http.StatusCreated, reply) } // update metadata in filer store @@ -196,7 +196,7 @@ func (fs *FilerServer) updateFilerStore(ctx context.Context, r *http.Request, w if dbErr := fs.filer.CreateEntry(ctx, entry, false); dbErr != nil { fs.filer.DeleteChunks(entry.Chunks) glog.V(0).Infof("failing to write %s to filer server : %v", path, dbErr) - writeJsonError(w, r, http.StatusInternalServerError, dbErr) + oldWriteJsonError(w, r, http.StatusInternalServerError, dbErr) err = dbErr return } @@ -228,7 +228,7 @@ func (fs *FilerServer) uploadToVolumeServer(r *http.Request, u *url.URL, auth se resp, doErr := util.Do(request) if doErr != nil { glog.Errorf("failing to connect to volume server %s: %v, %+v", r.RequestURI, doErr, r.Method) - writeJsonError(w, r, http.StatusInternalServerError, doErr) + oldWriteJsonError(w, r, http.StatusInternalServerError, doErr) err = doErr return } @@ -240,7 +240,7 @@ func (fs *FilerServer) uploadToVolumeServer(r *http.Request, u *url.URL, auth se respBody, raErr := ioutil.ReadAll(resp.Body) if raErr != nil { glog.V(0).Infoln("failing to upload to volume server", r.RequestURI, raErr.Error()) - writeJsonError(w, r, http.StatusInternalServerError, raErr) + oldWriteJsonError(w, r, http.StatusInternalServerError, raErr) err = raErr return } @@ -248,14 +248,14 @@ func (fs *FilerServer) uploadToVolumeServer(r *http.Request, u *url.URL, auth se unmarshalErr := json.Unmarshal(respBody, &ret) if unmarshalErr != nil { glog.V(0).Infoln("failing to read upload resonse", r.RequestURI, string(respBody)) - writeJsonError(w, r, http.StatusInternalServerError, unmarshalErr) + oldWriteJsonError(w, r, http.StatusInternalServerError, unmarshalErr) err = unmarshalErr return } if ret.Error != "" { err = errors.New(ret.Error) glog.V(0).Infoln("failing to post to volume server", r.RequestURI, ret.Error) - writeJsonError(w, r, http.StatusInternalServerError, err) + oldWriteJsonError(w, r, http.StatusInternalServerError, err) return } // find correct final path @@ -267,7 +267,7 @@ func (fs *FilerServer) uploadToVolumeServer(r *http.Request, u *url.URL, auth se err = fmt.Errorf("can not to write to folder %s without a file name", path) fs.filer.DeleteFileByFileId(fileId) glog.V(0).Infoln("Can not to write to folder", path, "without a file name!") - writeJsonError(w, r, http.StatusInternalServerError, err) + oldWriteJsonError(w, r, http.StatusInternalServerError, err) return } } @@ -299,7 +299,7 @@ func (fs *FilerServer) DeleteHandler(w http.ResponseWriter, r *http.Request) { if err == filer2.ErrNotFound { httpStatus = http.StatusNotFound } - writeJsonError(w, r, httpStatus, err) + oldWriteJsonError(w, r, httpStatus, err) return } diff --git a/weed/server/filer_server_handlers_write_autochunk.go b/weed/server/filer_server_handlers_write_autochunk.go index 25c0a4b4d..9e8b745c3 100644 --- a/weed/server/filer_server_handlers_write_autochunk.go +++ b/weed/server/filer_server_handlers_write_autochunk.go @@ -57,9 +57,9 @@ func (fs *FilerServer) autoChunk(ctx context.Context, w http.ResponseWriter, r * reply, err := fs.doAutoChunk(ctx, w, r, contentLength, chunkSize, replication, collection, dataCenter) if err != nil { - writeJsonError(w, r, http.StatusInternalServerError, err) + oldWriteJsonError(w, r, http.StatusInternalServerError, err) } else if reply != nil { - writeJsonQuiet(w, r, http.StatusCreated, reply) + oldWriteJsonQuiet(w, r, http.StatusCreated, reply) } return true } diff --git a/weed/server/master_server.go b/weed/server/master_server.go index b3cc310e6..1503a1b3f 100644 --- a/weed/server/master_server.go +++ b/weed/server/master_server.go @@ -107,17 +107,17 @@ func NewMasterServer(r *mux.Router, option *MasterOption, peers []string) *Maste handleStaticResources2(r) r.HandleFunc("/", ms.proxyToLeader(ms.uiStatusHandler)) r.HandleFunc("/ui/index.html", ms.uiStatusHandler) - r.HandleFunc("/dir/assign", ms.proxyToLeader(ms.guard.WhiteList(ms.dirAssignHandler))) - r.HandleFunc("/dir/lookup", ms.guard.WhiteList(ms.dirLookupHandler)) - r.HandleFunc("/dir/status", ms.proxyToLeader(ms.guard.WhiteList(ms.dirStatusHandler))) - r.HandleFunc("/col/delete", ms.proxyToLeader(ms.guard.WhiteList(ms.collectionDeleteHandler))) - r.HandleFunc("/vol/grow", ms.proxyToLeader(ms.guard.WhiteList(ms.volumeGrowHandler))) - r.HandleFunc("/vol/status", ms.proxyToLeader(ms.guard.WhiteList(ms.volumeStatusHandler))) - r.HandleFunc("/vol/vacuum", ms.proxyToLeader(ms.guard.WhiteList(ms.volumeVacuumHandler))) - r.HandleFunc("/submit", ms.guard.WhiteList(ms.submitFromMasterServerHandler)) - r.HandleFunc("/stats/health", ms.guard.WhiteList(statsHealthHandler)) - r.HandleFunc("/stats/counter", ms.guard.WhiteList(statsCounterHandler)) - r.HandleFunc("/stats/memory", ms.guard.WhiteList(statsMemoryHandler)) + r.HandleFunc("/dir/assign", ms.proxyToLeader(ms.guard.OldWhiteList(ms.dirAssignHandler))) + r.HandleFunc("/dir/lookup", ms.guard.OldWhiteList(ms.dirLookupHandler)) + r.HandleFunc("/dir/status", ms.proxyToLeader(ms.guard.OldWhiteList(ms.dirStatusHandler))) + r.HandleFunc("/col/delete", ms.proxyToLeader(ms.guard.OldWhiteList(ms.collectionDeleteHandler))) + r.HandleFunc("/vol/grow", ms.proxyToLeader(ms.guard.OldWhiteList(ms.volumeGrowHandler))) + r.HandleFunc("/vol/status", ms.proxyToLeader(ms.guard.OldWhiteList(ms.volumeStatusHandler))) + r.HandleFunc("/vol/vacuum", ms.proxyToLeader(ms.guard.OldWhiteList(ms.volumeVacuumHandler))) + r.HandleFunc("/submit", ms.guard.OldWhiteList(ms.submitFromMasterServerHandler)) + r.HandleFunc("/stats/health", ms.guard.OldWhiteList(statsHealthHandler)) + r.HandleFunc("/stats/counter", ms.guard.OldWhiteList(statsCounterHandler)) + r.HandleFunc("/stats/memory", ms.guard.OldWhiteList(statsMemoryHandler)) r.HandleFunc("/{fileId}", ms.redirectHandler) } @@ -157,7 +157,7 @@ func (ms *MasterServer) proxyToLeader(f func(w http.ResponseWriter, r *http.Requ defer func() { <-ms.bounedLeaderChan }() targetUrl, err := url.Parse("http://" + ms.Topo.RaftServer.Leader()) if err != nil { - writeJsonError(w, r, http.StatusInternalServerError, + oldWriteJsonError(w, r, http.StatusInternalServerError, fmt.Errorf("Leader URL http://%s Parse Error: %v", ms.Topo.RaftServer.Leader(), err)) return } @@ -175,7 +175,7 @@ func (ms *MasterServer) proxyToLeader(f func(w http.ResponseWriter, r *http.Requ proxy.ServeHTTP(w, r) } else { // drop it to the floor - // writeJsonError(w, r, errors.New(ms.Topo.RaftServer.Name()+" does not know Leader yet:"+ms.Topo.RaftServer.Leader())) + // oldWriteJsonError(w, r, errors.New(ms.Topo.RaftServer.Name()+" does not know Leader yet:"+ms.Topo.RaftServer.Leader())) } } } diff --git a/weed/server/master_server_handlers.go b/weed/server/master_server_handlers.go index 514d86800..2f4b33fa1 100644 --- a/weed/server/master_server_handlers.go +++ b/weed/server/master_server_handlers.go @@ -55,7 +55,7 @@ func (ms *MasterServer) dirLookupHandler(w http.ResponseWriter, r *http.Request) isRead := forRead == "yes" ms.maybeAddJwtAuthorization(w, fileId, !isRead) } - writeJsonQuiet(w, r, httpStatus, location) + oldWriteJsonQuiet(w, r, httpStatus, location) } // findVolumeLocation finds the volume location from master topo if it is leader, @@ -107,20 +107,20 @@ func (ms *MasterServer) dirAssignHandler(w http.ResponseWriter, r *http.Request) option, err := ms.getVolumeGrowOption(r) if err != nil { - writeJsonQuiet(w, r, http.StatusNotAcceptable, operation.AssignResult{Error: err.Error()}) + oldWriteJsonQuiet(w, r, http.StatusNotAcceptable, operation.AssignResult{Error: err.Error()}) return } if !ms.Topo.HasWritableVolume(option) { if ms.Topo.FreeSpace() <= 0 { - writeJsonQuiet(w, r, http.StatusNotFound, operation.AssignResult{Error: "No free volumes left!"}) + oldWriteJsonQuiet(w, r, http.StatusNotFound, operation.AssignResult{Error: "No free volumes left!"}) return } ms.vgLock.Lock() defer ms.vgLock.Unlock() if !ms.Topo.HasWritableVolume(option) { if _, err = ms.vg.AutomaticGrowByType(option, ms.grpcDialOption, ms.Topo, writableVolumeCount); err != nil { - writeJsonError(w, r, http.StatusInternalServerError, + oldWriteJsonError(w, r, http.StatusInternalServerError, fmt.Errorf("Cannot grow volume group! %v", err)) return } @@ -129,9 +129,9 @@ func (ms *MasterServer) dirAssignHandler(w http.ResponseWriter, r *http.Request) fid, count, dn, err := ms.Topo.PickForWrite(requestedCount, option) if err == nil { ms.maybeAddJwtAuthorization(w, fid, true) - writeJsonQuiet(w, r, http.StatusOK, operation.AssignResult{Fid: fid, Url: dn.Url(), PublicUrl: dn.PublicUrl, Count: count}) + oldWriteJsonQuiet(w, r, http.StatusOK, operation.AssignResult{Fid: fid, Url: dn.Url(), PublicUrl: dn.PublicUrl, Count: count}) } else { - writeJsonQuiet(w, r, http.StatusNotAcceptable, operation.AssignResult{Error: err.Error()}) + oldWriteJsonQuiet(w, r, http.StatusNotAcceptable, operation.AssignResult{Error: err.Error()}) } } diff --git a/weed/server/master_server_handlers_admin.go b/weed/server/master_server_handlers_admin.go index 44a04cb86..a13f511fb 100644 --- a/weed/server/master_server_handlers_admin.go +++ b/weed/server/master_server_handlers_admin.go @@ -21,7 +21,7 @@ func (ms *MasterServer) collectionDeleteHandler(w http.ResponseWriter, r *http.R collectionName := r.FormValue("collection") collection, ok := ms.Topo.FindCollection(collectionName) if !ok { - writeJsonError(w, r, http.StatusBadRequest, fmt.Errorf("collection %s does not exist", collectionName)) + oldWriteJsonError(w, r, http.StatusBadRequest, fmt.Errorf("collection %s does not exist", collectionName)) return } for _, server := range collection.ListVolumeServers() { @@ -32,7 +32,7 @@ func (ms *MasterServer) collectionDeleteHandler(w http.ResponseWriter, r *http.R return deleteErr }) if err != nil { - writeJsonError(w, r, http.StatusInternalServerError, err) + oldWriteJsonError(w, r, http.StatusInternalServerError, err) return } } @@ -46,7 +46,7 @@ func (ms *MasterServer) dirStatusHandler(w http.ResponseWriter, r *http.Request) m := make(map[string]interface{}) m["Version"] = util.VERSION m["Topology"] = ms.Topo.ToMap() - writeJsonQuiet(w, r, http.StatusOK, m) + oldWriteJsonQuiet(w, r, http.StatusOK, m) } func (ms *MasterServer) volumeVacuumHandler(w http.ResponseWriter, r *http.Request) { @@ -57,7 +57,7 @@ func (ms *MasterServer) volumeVacuumHandler(w http.ResponseWriter, r *http.Reque gcThreshold, err = strconv.ParseFloat(gcString, 32) if err != nil { glog.V(0).Infof("garbageThreshold %s is not a valid float number: %v", gcString, err) - writeJsonError(w, r, http.StatusNotAcceptable, fmt.Errorf("garbageThreshold %s is not a valid float number", gcString)) + oldWriteJsonError(w, r, http.StatusNotAcceptable, fmt.Errorf("garbageThreshold %s is not a valid float number", gcString)) return } } @@ -70,7 +70,7 @@ func (ms *MasterServer) volumeGrowHandler(w http.ResponseWriter, r *http.Request count := 0 option, err := ms.getVolumeGrowOption(r) if err != nil { - writeJsonError(w, r, http.StatusNotAcceptable, err) + oldWriteJsonError(w, r, http.StatusNotAcceptable, err) return } @@ -85,9 +85,9 @@ func (ms *MasterServer) volumeGrowHandler(w http.ResponseWriter, r *http.Request } if err != nil { - writeJsonError(w, r, http.StatusNotAcceptable, err) + oldWriteJsonError(w, r, http.StatusNotAcceptable, err) } else { - writeJsonQuiet(w, r, http.StatusOK, map[string]interface{}{"count": count}) + oldWriteJsonQuiet(w, r, http.StatusOK, map[string]interface{}{"count": count}) } } @@ -95,7 +95,7 @@ func (ms *MasterServer) volumeStatusHandler(w http.ResponseWriter, r *http.Reque m := make(map[string]interface{}) m["Version"] = util.VERSION m["Volumes"] = ms.Topo.ToVolumeMap() - writeJsonQuiet(w, r, http.StatusOK, m) + oldWriteJsonQuiet(w, r, http.StatusOK, m) } func (ms *MasterServer) redirectHandler(w http.ResponseWriter, r *http.Request) { @@ -112,7 +112,7 @@ func (ms *MasterServer) redirectHandler(w http.ResponseWriter, r *http.Request) } http.Redirect(w, r, url, http.StatusMovedPermanently) } else { - writeJsonError(w, r, http.StatusNotFound, fmt.Errorf("volume id %s not found: %s", vid, location.Error)) + oldWriteJsonError(w, r, http.StatusNotFound, fmt.Errorf("volume id %s not found: %s", vid, location.Error)) } } @@ -128,7 +128,7 @@ func (ms *MasterServer) submitFromMasterServerHandler(w http.ResponseWriter, r * } else { masterUrl, err := ms.Topo.Leader() if err != nil { - writeJsonError(w, r, http.StatusInternalServerError, err) + oldWriteJsonError(w, r, http.StatusInternalServerError, err) } else { submitForClientHandler(w, r, masterUrl, ms.grpcDialOption) } diff --git a/weed/server/raft_server_handlers.go b/weed/server/raft_server_handlers.go index fd38cb977..bfb310605 100644 --- a/weed/server/raft_server_handlers.go +++ b/weed/server/raft_server_handlers.go @@ -18,5 +18,5 @@ func (s *RaftServer) StatusHandler(w http.ResponseWriter, r *http.Request) { if leader, e := s.topo.Leader(); e == nil { ret.Leader = leader } - writeJsonQuiet(w, r, http.StatusOK, ret) + oldWriteJsonQuiet(w, r, http.StatusOK, ret) } diff --git a/weed/server/volume_server.go b/weed/server/volume_server.go index 0fdcf662a..fac2e7b43 100644 --- a/weed/server/volume_server.go +++ b/weed/server/volume_server.go @@ -76,16 +76,16 @@ func NewVolumeServer(adminMux, publicMux *http.ServeMux, ip string, if signingKey == "" || enableUiAccess { // only expose the volume server details for safe environments adminMux.HandleFunc("/ui/index.html", vs.uiStatusHandler) - adminMux.HandleFunc("/status", vs.guard.WhiteList(vs.statusHandler)) - adminMux.HandleFunc("/stats/counter", vs.guard.WhiteList(statsCounterHandler)) - adminMux.HandleFunc("/stats/memory", vs.guard.WhiteList(statsMemoryHandler)) - adminMux.HandleFunc("/stats/disk", vs.guard.WhiteList(vs.statsDiskHandler)) + adminMux.HandleFunc("/status", vs.guard.OldWhiteList(vs.statusHandler)) + adminMux.HandleFunc("/stats/counter", vs.guard.OldWhiteList(statsCounterHandler)) + adminMux.HandleFunc("/stats/memory", vs.guard.OldWhiteList(statsMemoryHandler)) + adminMux.HandleFunc("/stats/disk", vs.guard.OldWhiteList(vs.statsDiskHandler)) } - adminMux.HandleFunc("/", vs.privateStoreHandler) + adminMux.HandleFunc("/", vs.oldPrivateStoreHandler) if publicMux != adminMux { // separated admin and public port handleStaticResources(publicMux) - publicMux.HandleFunc("/", vs.publicReadOnlyHandler) + publicMux.HandleFunc("/", vs.oldPublicReadOnlyHandler) } go vs.heartbeat() diff --git a/weed/server/volume_server_fasthttp_handlers.go b/weed/server/volume_server_fasthttp_handlers.go new file mode 100644 index 000000000..bfd574e40 --- /dev/null +++ b/weed/server/volume_server_fasthttp_handlers.go @@ -0,0 +1,81 @@ +package weed_server + +import ( + "strings" + + "github.com/valyala/fasthttp" + + "github.com/chrislusf/seaweedfs/weed/glog" + "github.com/chrislusf/seaweedfs/weed/security" + "github.com/chrislusf/seaweedfs/weed/stats" +) + +func (vs *VolumeServer) HandleFastHTTP(ctx *fasthttp.RequestCtx) { + + switch string(ctx.Method()) { + case "GET", "HEAD": + vs.fastGetOrHeadHandler(ctx) + case "DELETE": + stats.DeleteRequest() + vs.guard.WhiteList(vs.DeleteHandler)(ctx) + case "PUT", "POST": + stats.WriteRequest() + vs.guard.WhiteList(vs.fastPostHandler)(ctx) + } + +} + +func (vs *VolumeServer) publicReadOnlyHandler(ctx *fasthttp.RequestCtx) { + switch string(ctx.Method()) { + case "GET": + stats.ReadRequest() + vs.fastGetOrHeadHandler(ctx) + case "HEAD": + stats.ReadRequest() + vs.fastGetOrHeadHandler(ctx) + } +} + +func (vs *VolumeServer) maybeCheckJwtAuthorization(ctx *fasthttp.RequestCtx, vid, fid string, isWrite bool) bool { + + var signingKey security.SigningKey + + if isWrite { + if len(vs.guard.SigningKey) == 0 { + return true + } else { + signingKey = vs.guard.SigningKey + } + } else { + if len(vs.guard.ReadSigningKey) == 0 { + return true + } else { + signingKey = vs.guard.ReadSigningKey + } + } + + tokenStr := security.GetJwt(ctx) + if tokenStr == "" { + glog.V(1).Infof("missing jwt from %s", ctx.RemoteAddr()) + return false + } + + token, err := security.DecodeJwt(signingKey, tokenStr) + if err != nil { + glog.V(1).Infof("jwt verification error from %s: %v", ctx.RemoteAddr(), err) + return false + } + if !token.Valid { + glog.V(1).Infof("jwt invalid from %s: %v", ctx.RemoteAddr(), tokenStr) + return false + } + + if sc, ok := token.Claims.(*security.SeaweedFileIdClaims); ok { + if sepIndex := strings.LastIndex(fid, "_"); sepIndex > 0 { + fid = fid[:sepIndex] + } + return sc.Fid == vid+","+fid + } + glog.V(1).Infof("unexpected jwt from %s: %v", ctx.RemoteAddr(), tokenStr) + return false +} diff --git a/weed/server/volume_server_fasthttp_handlers_read.go b/weed/server/volume_server_fasthttp_handlers_read.go new file mode 100644 index 000000000..f58b705f1 --- /dev/null +++ b/weed/server/volume_server_fasthttp_handlers_read.go @@ -0,0 +1,366 @@ +package weed_server + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "mime" + "mime/multipart" + "net/http" + "net/url" + "path" + "strconv" + "strings" + "time" + + "github.com/valyala/fasthttp" + + "github.com/chrislusf/seaweedfs/weed/glog" + "github.com/chrislusf/seaweedfs/weed/images" + "github.com/chrislusf/seaweedfs/weed/operation" + "github.com/chrislusf/seaweedfs/weed/stats" + "github.com/chrislusf/seaweedfs/weed/storage/needle" + "github.com/chrislusf/seaweedfs/weed/util" +) + +func (vs *VolumeServer) fastGetOrHeadHandler(ctx *fasthttp.RequestCtx) { + + stats.VolumeServerRequestCounter.WithLabelValues("get").Inc() + start := time.Now() + defer func() { stats.VolumeServerRequestHistogram.WithLabelValues("get").Observe(time.Since(start).Seconds()) }() + + requestPath := string(ctx.Path()) + n := new(needle.Needle) + vid, fid, filename, ext, _ := parseURLPath(requestPath) + + if !vs.maybeCheckJwtAuthorization(ctx, vid, fid, false) { + writeJsonError(ctx, http.StatusUnauthorized, errors.New("wrong jwt")) + return + } + + volumeId, err := needle.NewVolumeId(vid) + if err != nil { + glog.V(2).Infof("parsing volumd id %s error: %v", err, requestPath) + ctx.SetStatusCode(http.StatusBadRequest) + return + } + err = n.ParsePath(fid) + if err != nil { + glog.V(2).Infof("parsing fid %s error: %v", err, requestPath) + ctx.SetStatusCode(http.StatusBadRequest) + return + } + + // glog.V(4).Infoln("volume", volumeId, "reading", n) + hasVolume := vs.store.HasVolume(volumeId) + _, hasEcVolume := vs.store.FindEcVolume(volumeId) + if !hasVolume && !hasEcVolume { + if !vs.ReadRedirect { + glog.V(2).Infoln("volume is not local:", err, requestPath) + ctx.SetStatusCode(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 := ctx.FormValue("collection"); c != nil { + arg.Set("collection", string(c)) + } + u.RawQuery = arg.Encode() + ctx.Redirect(u.String(), http.StatusMovedPermanently) + + } else { + glog.V(2).Infof("lookup %s error: %v", requestPath, err) + ctx.SetStatusCode(http.StatusNotFound) + } + return + } + + cookie := n.Cookie + var count int + if hasVolume { + count, err = vs.store.ReadVolumeNeedle(volumeId, n) + } else if hasEcVolume { + count, err = vs.store.ReadEcShardNeedle(context.Background(), volumeId, n) + } + // glog.V(4).Infoln("read bytes", count, "error", err) + if err != nil || count < 0 { + glog.V(0).Infof("read %s isNormalVolume %v error: %v", requestPath, hasVolume, err) + ctx.SetStatusCode(http.StatusNotFound) + return + } + if n.Cookie != cookie { + glog.V(0).Infof("request %s with cookie:%x expected:%x agent %s", requestPath, cookie, n.Cookie, string(ctx.UserAgent())) + ctx.SetStatusCode(http.StatusNotFound) + return + } + if n.LastModified != 0 { + ctx.Response.Header.Set("Last-Modified", time.Unix(int64(n.LastModified), 0).UTC().Format(http.TimeFormat)) + if ctx.Response.Header.Peek("If-Modified-Since") != nil { + if t, parseError := time.Parse(http.TimeFormat, string(ctx.Response.Header.Peek("If-Modified-Since"))); parseError == nil { + if t.Unix() >= int64(n.LastModified) { + ctx.SetStatusCode(http.StatusNotModified) + return + } + } + } + } + if inm := ctx.Response.Header.Peek("If-None-Match"); inm != nil && string(inm) == "\""+n.Etag()+"\"" { + ctx.SetStatusCode(http.StatusNotModified) + return + } + eTagMd5 := ctx.Response.Header.Peek("ETag-MD5") + if eTagMd5 != nil && string(eTagMd5) == "True" { + fastSetEtag(ctx, n.MD5()) + } else { + fastSetEtag(ctx, 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 { + ctx.Response.Header.Set(k, v) + } + } + + if vs.fastTryHandleChunkedFile(n, filename, ctx) { + 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() { + acceptEncoding := ctx.Request.Header.Peek("Accept-Encoding") + if acceptEncoding != nil && strings.Contains(string(acceptEncoding), "gzip") { + ctx.Response.Header.Set("Content-Encoding", "gzip") + } else { + if n.Data, err = util.UnGzipData(n.Data); err != nil { + glog.V(0).Infoln("ungzip error:", err, requestPath) + } + } + } + } + + rs := fastConditionallyResizeImages(bytes.NewReader(n.Data), ext, ctx) + + if e := fastWriteResponseContent(filename, mtype, rs, ctx); e != nil { + glog.V(2).Infoln("response write error:", e) + } + +} + +func (vs *VolumeServer) fastTryHandleChunkedFile(n *needle.Needle, fileName string, ctx *fasthttp.RequestCtx) (processed bool) { + if !n.IsChunkedManifest() || string(ctx.FormValue("cm")) == "false" { + return false + } + + chunkManifest, e := operation.LoadChunkManifest(n.Data, n.IsGzipped()) + if e != nil { + glog.V(0).Infof("load chunked manifest (%s) error: %v", string(ctx.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 + } + } + + ctx.Response.Header.Set("X-File-Store", "chunked") + + chunkedFileReader := &operation.ChunkedFileReader{ + Manifest: chunkManifest, + Master: vs.GetMaster(), + } + defer chunkedFileReader.Close() + + rs := fastConditionallyResizeImages(chunkedFileReader, ext, ctx) + + if e := fastWriteResponseContent(fileName, mType, rs, ctx); e != nil { + glog.V(2).Infoln("response write error:", e) + } + return true +} + +func fastConditionallyResizeImages(originalDataReaderSeeker io.ReadSeeker, ext string, ctx *fasthttp.RequestCtx) 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 + formWidth, formHeight := ctx.FormValue("width"), ctx.FormValue("height") + if formWidth != nil { + width, _ = strconv.Atoi(string(formWidth)) + } + if formHeight != nil { + height, _ = strconv.Atoi(string(formHeight)) + } + formMode := ctx.FormValue("mode") + rs, _, _ = images.Resized(ext, originalDataReaderSeeker, width, height, string(formMode)) + } + return rs +} + +func fastWriteResponseContent(filename, mimeType string, rs io.ReadSeeker, ctx *fasthttp.RequestCtx) error { + totalSize, e := rs.Seek(0, 2) + if mimeType == "" { + if ext := path.Ext(filename); ext != "" { + mimeType = mime.TypeByExtension(ext) + } + } + if mimeType != "" { + ctx.Response.Header.Set("Content-Type", mimeType) + } + if filename != "" { + contentDisposition := "inline" + dlFormValue := ctx.FormValue("dl") + if dlFormValue != nil { + if dl, _ := strconv.ParseBool(string(dlFormValue)); dl { + contentDisposition = "attachment" + } + } + ctx.Response.Header.Set("Content-Disposition", contentDisposition+`; filename="`+fileNameEscaper.Replace(filename)+`"`) + } + ctx.Response.Header.Set("Accept-Ranges", "bytes") + if ctx.IsHead() { + ctx.Response.Header.Set("Content-Length", strconv.FormatInt(totalSize, 10)) + return nil + } + rangeReq := ctx.FormValue("Range") + if rangeReq == nil { + ctx.Response.Header.Set("Content-Length", strconv.FormatInt(totalSize, 10)) + if _, e = rs.Seek(0, 0); e != nil { + return e + } + _, e = io.Copy(ctx.Response.BodyWriter(), rs) + return e + } + + //the rest is dealing with partial content request + //mostly copy from src/pkg/net/http/fs.go + ranges, err := parseRange(string(rangeReq), totalSize) + if err != nil { + ctx.Response.SetStatusCode(http.StatusRequestedRangeNotSatisfiable) + ctxError(ctx, err.Error(), http.StatusRequestedRangeNotSatisfiable) + return nil + } + if sumRangesSize(ranges) > totalSize { + // The total number of bytes in all the ranges + // is larger than the size of the file by + // itself, so this is probably an attack, or a + // dumb client. Ignore the range request. + return nil + } + if len(ranges) == 0 { + return nil + } + if len(ranges) == 1 { + // RFC 2616, Section 14.16: + // "When an HTTP message includes the content of a single + // range (for example, a response to a request for a + // single range, or to a request for a set of ranges + // that overlap without any holes), this content is + // transmitted with a Content-Range header, and a + // Content-Length header showing the number of bytes + // actually transferred. + // ... + // A response to a request for a single range MUST NOT + // be sent using the multipart/byteranges media type." + ra := ranges[0] + ctx.Response.Header.Set("Content-Length", strconv.FormatInt(ra.length, 10)) + ctx.Response.Header.Set("Content-Range", ra.contentRange(totalSize)) + ctx.Response.SetStatusCode(http.StatusPartialContent) + if _, e = rs.Seek(ra.start, 0); e != nil { + return e + } + + _, e = io.CopyN(ctx.Response.BodyWriter(), rs, ra.length) + return e + } + // process multiple ranges + for _, ra := range ranges { + if ra.start > totalSize { + ctxError(ctx, "Out of Range", http.StatusRequestedRangeNotSatisfiable) + return nil + } + } + sendSize := rangesMIMESize(ranges, mimeType, totalSize) + pr, pw := io.Pipe() + mw := multipart.NewWriter(pw) + ctx.Response.Header.Set("Content-Type", "multipart/byteranges; boundary="+mw.Boundary()) + sendContent := pr + defer pr.Close() // cause writing goroutine to fail and exit if CopyN doesn't finish. + go func() { + for _, ra := range ranges { + part, e := mw.CreatePart(ra.mimeHeader(mimeType, totalSize)) + if e != nil { + pw.CloseWithError(e) + return + } + if _, e = rs.Seek(ra.start, 0); e != nil { + pw.CloseWithError(e) + return + } + if _, e = io.CopyN(part, rs, ra.length); e != nil { + pw.CloseWithError(e) + return + } + } + mw.Close() + pw.Close() + }() + if ctx.Response.Header.Peek("Content-Encoding") == nil { + ctx.Response.Header.Set("Content-Length", strconv.FormatInt(sendSize, 10)) + } + ctx.Response.Header.SetStatusCode(http.StatusPartialContent) + _, e = io.CopyN(ctx.Response.BodyWriter(), sendContent, sendSize) + return e +} + +func fastSetEtag(ctx *fasthttp.RequestCtx, etag string) { + if etag != "" { + if strings.HasPrefix(etag, "\"") { + ctx.Response.Header.Set("ETag", etag) + } else { + ctx.Response.Header.Set("ETag", "\""+etag+"\"") + } + } +} + +func ctxError(ctx *fasthttp.RequestCtx, error string, code int) { + ctx.Response.Header.Set("Content-Type", "text/plain; charset=utf-8") + ctx.Response.Header.Set("X-Content-Type-Options", "nosniff") + ctx.Response.SetStatusCode(code) + fmt.Fprintln(ctx.Response.BodyWriter(), error) +} diff --git a/weed/server/volume_server_fasthttp_handlers_write.go b/weed/server/volume_server_fasthttp_handlers_write.go new file mode 100644 index 000000000..53aa8e98d --- /dev/null +++ b/weed/server/volume_server_fasthttp_handlers_write.go @@ -0,0 +1,156 @@ +package weed_server + +import ( + "context" + "errors" + "fmt" + "net/http" + "strconv" + "time" + + "github.com/valyala/fasthttp" + + "github.com/chrislusf/seaweedfs/weed/glog" + "github.com/chrislusf/seaweedfs/weed/operation" + "github.com/chrislusf/seaweedfs/weed/stats" + "github.com/chrislusf/seaweedfs/weed/storage/needle" + "github.com/chrislusf/seaweedfs/weed/topology" +) + +func (vs *VolumeServer) fastPostHandler(ctx *fasthttp.RequestCtx) { + + stats.VolumeServerRequestCounter.WithLabelValues("post").Inc() + start := time.Now() + defer func() { + stats.VolumeServerRequestHistogram.WithLabelValues("post").Observe(time.Since(start).Seconds()) + }() + + requestPath := string(ctx.Path()) + + vid, fid, _, _, _ := parseURLPath(requestPath) + volumeId, ve := needle.NewVolumeId(vid) + if ve != nil { + glog.V(0).Infoln("NewVolumeId error:", ve) + writeJsonError(ctx, http.StatusBadRequest, ve) + return + } + + if !vs.maybeCheckJwtAuthorization(ctx, vid, fid, true) { + writeJsonError(ctx, http.StatusUnauthorized, errors.New("wrong jwt")) + return + } + + needle, originalSize, ne := needle.CreateNeedleFromRequest(ctx, vs.FixJpgOrientation, vs.fileSizeLimitBytes) + if ne != nil { + writeJsonError(ctx, http.StatusBadRequest, ne) + return + } + + ret := operation.UploadResult{} + _, isUnchanged, writeError := topology.OldReplicatedWrite(vs.GetMaster(), vs.store, volumeId, needle, r) + + // http 304 status code does not allow body + if writeError == nil && isUnchanged { + ctx.SetStatusCode(http.StatusNotModified) + return + } + + httpStatus := http.StatusCreated + if writeError != nil { + httpStatus = http.StatusInternalServerError + ret.Error = writeError.Error() + } + if needle.HasName() { + ret.Name = string(needle.Name) + } + ret.Size = uint32(originalSize) + ret.ETag = needle.Etag() + fastSetEtag(ctx, ret.ETag) + writeJsonQuiet(ctx, httpStatus, ret) +} + +func (vs *VolumeServer) DeleteHandler(ctx *fasthttp.RequestCtx) { + + stats.VolumeServerRequestCounter.WithLabelValues("delete").Inc() + start := time.Now() + defer func() { + stats.VolumeServerRequestHistogram.WithLabelValues("delete").Observe(time.Since(start).Seconds()) + }() + + requestPath := string(ctx.Path()) + n := new(needle.Needle) + vid, fid, _, _, _ := parseURLPath(requestPath) + volumeId, _ := needle.NewVolumeId(vid) + n.ParsePath(fid) + + if !vs.maybeCheckJwtAuthorization(ctx, vid, fid, true) { + writeJsonError(ctx, http.StatusUnauthorized, errors.New("wrong jwt")) + return + } + + // glog.V(2).Infof("volume %s deleting %s", vid, n) + + cookie := n.Cookie + + ecVolume, hasEcVolume := vs.store.FindEcVolume(volumeId) + + if hasEcVolume { + count, err := vs.store.DeleteEcShardNeedle(context.Background(), ecVolume, n, cookie) + writeDeleteResult(err, count, ctx) + return + } + + _, ok := vs.store.ReadVolumeNeedle(volumeId, n) + if ok != nil { + m := make(map[string]uint32) + m["size"] = 0 + writeJsonQuiet(ctx, http.StatusNotFound, m) + return + } + + if n.Cookie != cookie { + glog.V(0).Infof("delete %s with unmaching cookie from %s agent %s", requestPath, ctx.RemoteAddr(), ctx.UserAgent()) + writeJsonError(ctx, http.StatusBadRequest, errors.New("File Random Cookie does not match.")) + return + } + + count := int64(n.Size) + + if n.IsChunkedManifest() { + chunkManifest, e := operation.LoadChunkManifest(n.Data, n.IsGzipped()) + if e != nil { + writeJsonError(ctx, http.StatusInternalServerError, fmt.Errorf("Load chunks manifest error: %v", e)) + return + } + // make sure all chunks had deleted before delete manifest + if e := chunkManifest.DeleteChunks(vs.GetMaster(), vs.grpcDialOption); e != nil { + writeJsonError(ctx, http.StatusInternalServerError, fmt.Errorf("Delete chunks error: %v", e)) + return + } + count = chunkManifest.Size + } + + n.LastModified = uint64(time.Now().Unix()) + tsValue := ctx.FormValue("ts") + if tsValue != nil { + modifiedTime, err := strconv.ParseInt(string(tsValue), 10, 64) + if err == nil { + n.LastModified = uint64(modifiedTime) + } + } + + _, err := topology.ReplicatedDelete(vs.GetMaster(), vs.store, volumeId, n, ctx) + + writeDeleteResult(err, count, ctx) + +} + +func writeDeleteResult(err error, count int64, ctx *fasthttp.RequestCtx) { + if err == nil { + m := make(map[string]int64) + m["size"] = count + writeJsonQuiet(ctx, http.StatusAccepted, m) + } else { + writeJsonQuiet(ctx, http.StatusInternalServerError, fmt.Errorf("Deletion Failed: %v", err)) + } +} diff --git a/weed/server/volume_server_handlers.go b/weed/server/volume_server_handlers.go index 14ad27d42..e535b1ae7 100644 --- a/weed/server/volume_server_handlers.go +++ b/weed/server/volume_server_handlers.go @@ -24,32 +24,32 @@ security settings: */ -func (vs *VolumeServer) privateStoreHandler(w http.ResponseWriter, r *http.Request) { +func (vs *VolumeServer) oldPrivateStoreHandler(w http.ResponseWriter, r *http.Request) { switch r.Method { case "GET", "HEAD": stats.ReadRequest() - vs.GetOrHeadHandler(w, r) + vs.OldGetOrHeadHandler(w, r) case "DELETE": stats.DeleteRequest() - vs.guard.WhiteList(vs.DeleteHandler)(w, r) + vs.guard.OldWhiteList(vs.OldDeleteHandler)(w, r) case "PUT", "POST": stats.WriteRequest() - vs.guard.WhiteList(vs.PostHandler)(w, r) + vs.guard.OldWhiteList(vs.OldPostHandler)(w, r) } } -func (vs *VolumeServer) publicReadOnlyHandler(w http.ResponseWriter, r *http.Request) { +func (vs *VolumeServer) oldPublicReadOnlyHandler(w http.ResponseWriter, r *http.Request) { switch r.Method { case "GET": stats.ReadRequest() - vs.GetOrHeadHandler(w, r) + vs.OldGetOrHeadHandler(w, r) case "HEAD": stats.ReadRequest() - vs.GetOrHeadHandler(w, r) + vs.OldGetOrHeadHandler(w, r) } } -func (vs *VolumeServer) maybeCheckJwtAuthorization(r *http.Request, vid, fid string, isWrite bool) bool { +func (vs *VolumeServer) oldMaybeCheckJwtAuthorization(r *http.Request, vid, fid string, isWrite bool) bool { var signingKey security.SigningKey @@ -67,7 +67,7 @@ func (vs *VolumeServer) maybeCheckJwtAuthorization(r *http.Request, vid, fid str } } - tokenStr := security.GetJwt(r) + tokenStr := security.OldGetJwt(r) if tokenStr == "" { glog.V(1).Infof("missing jwt from %s", r.RemoteAddr) return false diff --git a/weed/server/volume_server_handlers_admin.go b/weed/server/volume_server_handlers_admin.go index 1938a34c4..ce675ede2 100644 --- a/weed/server/volume_server_handlers_admin.go +++ b/weed/server/volume_server_handlers_admin.go @@ -13,7 +13,7 @@ func (vs *VolumeServer) statusHandler(w http.ResponseWriter, r *http.Request) { m := make(map[string]interface{}) m["Version"] = util.VERSION m["Volumes"] = vs.store.VolumeInfos() - writeJsonQuiet(w, r, http.StatusOK, m) + oldWriteJsonQuiet(w, r, http.StatusOK, m) } func (vs *VolumeServer) statsDiskHandler(w http.ResponseWriter, r *http.Request) { @@ -26,5 +26,5 @@ func (vs *VolumeServer) statsDiskHandler(w http.ResponseWriter, r *http.Request) } } m["DiskStatuses"] = ds - writeJsonQuiet(w, r, http.StatusOK, m) + oldWriteJsonQuiet(w, r, http.StatusOK, m) } diff --git a/weed/server/volume_server_handlers_read.go b/weed/server/volume_server_handlers_read.go index d89d13a0d..ee8112b3e 100644 --- a/weed/server/volume_server_handlers_read.go +++ b/weed/server/volume_server_handlers_read.go @@ -27,7 +27,7 @@ import ( var fileNameEscaper = strings.NewReplacer("\\", "\\\\", "\"", "\\\"") -func (vs *VolumeServer) GetOrHeadHandler(w http.ResponseWriter, r *http.Request) { +func (vs *VolumeServer) OldGetOrHeadHandler(w http.ResponseWriter, r *http.Request) { stats.VolumeServerRequestCounter.WithLabelValues("get").Inc() start := time.Now() @@ -36,8 +36,8 @@ func (vs *VolumeServer) GetOrHeadHandler(w http.ResponseWriter, r *http.Request) n := new(needle.Needle) vid, fid, filename, ext, _ := parseURLPath(r.URL.Path) - if !vs.maybeCheckJwtAuthorization(r, vid, fid, false) { - writeJsonError(w, r, http.StatusUnauthorized, errors.New("wrong jwt")) + if !vs.oldMaybeCheckJwtAuthorization(r, vid, fid, false) { + oldWriteJsonError(w, r, http.StatusUnauthorized, errors.New("wrong jwt")) return } @@ -115,9 +115,9 @@ func (vs *VolumeServer) GetOrHeadHandler(w http.ResponseWriter, r *http.Request) return } if r.Header.Get("ETag-MD5") == "True" { - setEtag(w, n.MD5()) + oldSetEtag(w, n.MD5()) } else { - setEtag(w, n.Etag()) + oldSetEtag(w, n.Etag()) } if n.HasPairs() { diff --git a/weed/server/volume_server_handlers_write.go b/weed/server/volume_server_handlers_write.go index cd35255e5..eb24d1c07 100644 --- a/weed/server/volume_server_handlers_write.go +++ b/weed/server/volume_server_handlers_write.go @@ -16,7 +16,7 @@ import ( "github.com/chrislusf/seaweedfs/weed/topology" ) -func (vs *VolumeServer) PostHandler(w http.ResponseWriter, r *http.Request) { +func (vs *VolumeServer) OldPostHandler(w http.ResponseWriter, r *http.Request) { stats.VolumeServerRequestCounter.WithLabelValues("post").Inc() start := time.Now() @@ -26,7 +26,7 @@ func (vs *VolumeServer) PostHandler(w http.ResponseWriter, r *http.Request) { if e := r.ParseForm(); e != nil { glog.V(0).Infoln("form parse error:", e) - writeJsonError(w, r, http.StatusBadRequest, e) + oldWriteJsonError(w, r, http.StatusBadRequest, e) return } @@ -34,23 +34,23 @@ func (vs *VolumeServer) PostHandler(w http.ResponseWriter, r *http.Request) { volumeId, ve := needle.NewVolumeId(vid) if ve != nil { glog.V(0).Infoln("NewVolumeId error:", ve) - writeJsonError(w, r, http.StatusBadRequest, ve) + oldWriteJsonError(w, r, http.StatusBadRequest, ve) return } - if !vs.maybeCheckJwtAuthorization(r, vid, fid, true) { - writeJsonError(w, r, http.StatusUnauthorized, errors.New("wrong jwt")) + if !vs.oldMaybeCheckJwtAuthorization(r, vid, fid, true) { + oldWriteJsonError(w, r, http.StatusUnauthorized, errors.New("wrong jwt")) return } - needle, originalSize, ne := needle.CreateNeedleFromRequest(r, vs.FixJpgOrientation, vs.fileSizeLimitBytes) + needle, originalSize, ne := needle.OldCreateNeedleFromRequest(r, vs.FixJpgOrientation, vs.fileSizeLimitBytes) if ne != nil { - writeJsonError(w, r, http.StatusBadRequest, ne) + oldWriteJsonError(w, r, http.StatusBadRequest, ne) return } ret := operation.UploadResult{} - _, isUnchanged, writeError := topology.ReplicatedWrite(vs.GetMaster(), vs.store, volumeId, needle, r) + _, isUnchanged, writeError := topology.OldReplicatedWrite(vs.GetMaster(), vs.store, volumeId, needle, r) // http 304 status code does not allow body if writeError == nil && isUnchanged { @@ -68,11 +68,11 @@ func (vs *VolumeServer) PostHandler(w http.ResponseWriter, r *http.Request) { } ret.Size = uint32(originalSize) ret.ETag = needle.Etag() - setEtag(w, ret.ETag) - writeJsonQuiet(w, r, httpStatus, ret) + oldSetEtag(w, ret.ETag) + oldWriteJsonQuiet(w, r, httpStatus, ret) } -func (vs *VolumeServer) DeleteHandler(w http.ResponseWriter, r *http.Request) { +func (vs *VolumeServer) OldDeleteHandler(w http.ResponseWriter, r *http.Request) { stats.VolumeServerRequestCounter.WithLabelValues("delete").Inc() start := time.Now() @@ -85,8 +85,8 @@ func (vs *VolumeServer) DeleteHandler(w http.ResponseWriter, r *http.Request) { volumeId, _ := needle.NewVolumeId(vid) n.ParsePath(fid) - if !vs.maybeCheckJwtAuthorization(r, vid, fid, true) { - writeJsonError(w, r, http.StatusUnauthorized, errors.New("wrong jwt")) + if !vs.oldMaybeCheckJwtAuthorization(r, vid, fid, true) { + oldWriteJsonError(w, r, http.StatusUnauthorized, errors.New("wrong jwt")) return } @@ -98,7 +98,7 @@ func (vs *VolumeServer) DeleteHandler(w http.ResponseWriter, r *http.Request) { if hasEcVolume { count, err := vs.store.DeleteEcShardNeedle(context.Background(), ecVolume, n, cookie) - writeDeleteResult(err, count, w, r) + oldWriteDeleteResult(err, count, w, r) return } @@ -106,13 +106,13 @@ func (vs *VolumeServer) DeleteHandler(w http.ResponseWriter, r *http.Request) { if ok != nil { m := make(map[string]uint32) m["size"] = 0 - writeJsonQuiet(w, r, http.StatusNotFound, m) + oldWriteJsonQuiet(w, r, http.StatusNotFound, m) return } if n.Cookie != cookie { glog.V(0).Infoln("delete", r.URL.Path, "with unmaching cookie from ", r.RemoteAddr, "agent", r.UserAgent()) - writeJsonError(w, r, http.StatusBadRequest, errors.New("File Random Cookie does not match.")) + oldWriteJsonError(w, r, http.StatusBadRequest, errors.New("File Random Cookie does not match.")) return } @@ -121,12 +121,12 @@ func (vs *VolumeServer) DeleteHandler(w http.ResponseWriter, r *http.Request) { if n.IsChunkedManifest() { chunkManifest, e := operation.LoadChunkManifest(n.Data, n.IsGzipped()) if e != nil { - writeJsonError(w, r, http.StatusInternalServerError, fmt.Errorf("Load chunks manifest error: %v", e)) + oldWriteJsonError(w, r, http.StatusInternalServerError, fmt.Errorf("Load chunks manifest error: %v", e)) return } // make sure all chunks had deleted before delete manifest if e := chunkManifest.DeleteChunks(vs.GetMaster(), vs.grpcDialOption); e != nil { - writeJsonError(w, r, http.StatusInternalServerError, fmt.Errorf("Delete chunks error: %v", e)) + oldWriteJsonError(w, r, http.StatusInternalServerError, fmt.Errorf("Delete chunks error: %v", e)) return } count = chunkManifest.Size @@ -140,23 +140,23 @@ func (vs *VolumeServer) DeleteHandler(w http.ResponseWriter, r *http.Request) { } } - _, err := topology.ReplicatedDelete(vs.GetMaster(), vs.store, volumeId, n, r) + _, err := topology.OldReplicatedDelete(vs.GetMaster(), vs.store, volumeId, n, r) - writeDeleteResult(err, count, w, r) + oldWriteDeleteResult(err, count, w, r) } -func writeDeleteResult(err error, count int64, w http.ResponseWriter, r *http.Request) { +func oldWriteDeleteResult(err error, count int64, w http.ResponseWriter, r *http.Request) { if err == nil { m := make(map[string]int64) m["size"] = count - writeJsonQuiet(w, r, http.StatusAccepted, m) + oldWriteJsonQuiet(w, r, http.StatusAccepted, m) } else { - writeJsonError(w, r, http.StatusInternalServerError, fmt.Errorf("Deletion Failed: %v", err)) + oldWriteJsonError(w, r, http.StatusInternalServerError, fmt.Errorf("Deletion Failed: %v", err)) } } -func setEtag(w http.ResponseWriter, etag string) { +func oldSetEtag(w http.ResponseWriter, etag string) { if etag != "" { if strings.HasPrefix(etag, "\"") { w.Header().Set("ETag", etag) |
