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.

64 lines
2.1 KiB

  1. package weed_server
  2. import (
  3. "encoding/json"
  4. "io/ioutil"
  5. "net/http"
  6. "strings"
  7. "github.com/chrislusf/weed-fs/go/glog"
  8. "github.com/chrislusf/weed-fs/go/operation"
  9. "github.com/goraft/raft"
  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. glog.V(0).Infoln("Redirecting to", http.StatusMovedPermanently, "http://"+leader+req.URL.Path)
  40. http.Redirect(w, req, "http://"+leader+req.URL.Path, http.StatusMovedPermanently)
  41. } else {
  42. glog.V(0).Infoln("Error: Leader Unknown")
  43. http.Error(w, "Leader unknown", http.StatusInternalServerError)
  44. }
  45. }
  46. func (s *RaftServer) statusHandler(w http.ResponseWriter, r *http.Request) {
  47. ret := operation.ClusterStatusResult{
  48. IsLeader: s.topo.IsLeader(),
  49. Peers: s.Peers(),
  50. }
  51. if leader, e := s.topo.Leader(); e == nil {
  52. ret.Leader = leader
  53. }
  54. writeJsonQuiet(w, r, http.StatusOK, ret)
  55. }