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.

59 lines
1.9 KiB

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