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.

66 lines
2.2 KiB

  1. package weed_server
  2. import (
  3. "encoding/json"
  4. "io/ioutil"
  5. "net/http"
  6. "strings"
  7. "github.com/chrislusf/raft"
  8. "github.com/chrislusf/seaweedfs/weed/glog"
  9. "github.com/chrislusf/seaweedfs/weed/operation"
  10. )
  11. // Handles incoming RAFT joins.
  12. func (s *RaftServer) joinHandler(w http.ResponseWriter, req *http.Request) {
  13. glog.V(0).Infoln("Processing incoming join. Current Leader", s.raftServer.Leader(), "Self", s.raftServer.Name(), "Peers", s.raftServer.Peers())
  14. command := &raft.DefaultJoinCommand{}
  15. commandText, _ := ioutil.ReadAll(req.Body)
  16. glog.V(0).Info("Command:", string(commandText))
  17. if err := json.NewDecoder(strings.NewReader(string(commandText))).Decode(&command); err != nil {
  18. glog.V(0).Infoln("Error decoding json message:", err, string(commandText))
  19. http.Error(w, err.Error(), http.StatusInternalServerError)
  20. return
  21. }
  22. glog.V(0).Infoln("join command from Name", command.Name, "Connection", command.ConnectionString)
  23. if _, err := s.raftServer.Do(command); err != nil {
  24. switch err {
  25. case raft.NotLeaderError:
  26. s.redirectToLeader(w, req)
  27. default:
  28. glog.V(0).Infoln("Error processing join:", err)
  29. http.Error(w, err.Error(), http.StatusInternalServerError)
  30. }
  31. }
  32. }
  33. func (s *RaftServer) HandleFunc(pattern string, handler func(http.ResponseWriter, *http.Request)) {
  34. s.router.HandleFunc(pattern, handler)
  35. }
  36. func (s *RaftServer) redirectToLeader(w http.ResponseWriter, req *http.Request) {
  37. if leader, e := s.topo.Leader(); e == nil {
  38. //http.StatusMovedPermanently does not cause http POST following redirection
  39. learderLocation := "http://" + leader + req.URL.Path
  40. glog.V(0).Infoln("Redirecting to", learderLocation)
  41. writeJsonQuiet(w, req, http.StatusOK, learderLocation)
  42. // http.Redirect(w, req, "http://"+leader+req.URL.Path, http.StatusFound) // not working any more
  43. } else {
  44. glog.V(0).Infoln("Error: Leader Unknown")
  45. http.Error(w, "Leader unknown", http.StatusInternalServerError)
  46. }
  47. }
  48. func (s *RaftServer) statusHandler(w http.ResponseWriter, r *http.Request) {
  49. ret := operation.ClusterStatusResult{
  50. IsLeader: s.topo.IsLeader(),
  51. Peers: s.Peers(),
  52. }
  53. if leader, e := s.topo.Leader(); e == nil {
  54. ret.Leader = leader
  55. }
  56. writeJsonQuiet(w, r, http.StatusOK, ret)
  57. }