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.

115 lines
3.3 KiB

10 years ago
10 years ago
10 years ago
  1. // Commons for HTTP handling
  2. package rpcserver
  3. import (
  4. "bufio"
  5. "fmt"
  6. "net"
  7. "net/http"
  8. "runtime/debug"
  9. "time"
  10. . "github.com/tendermint/go-common"
  11. "github.com/tendermint/go-wire"
  12. "github.com/tendermint/tendermint/alert"
  13. . "github.com/tendermint/tendermint/rpc/types"
  14. )
  15. func StartHTTPServer(listenAddr string, handler http.Handler) (net.Listener, error) {
  16. log.Notice(Fmt("Starting RPC HTTP server on %v", listenAddr))
  17. listener, err := net.Listen("tcp", listenAddr)
  18. if err != nil {
  19. return nil, fmt.Errorf("Failed to listen to %v", listenAddr)
  20. }
  21. go func() {
  22. res := http.Serve(
  23. listener,
  24. RecoverAndLogHandler(handler),
  25. )
  26. log.Crit("RPC HTTP server stopped", "result", res)
  27. }()
  28. return listener, nil
  29. }
  30. func WriteRPCResponseHTTP(w http.ResponseWriter, res RPCResponse) {
  31. jsonBytes := wire.JSONBytesPretty(res)
  32. w.Header().Set("Content-Type", "application/json")
  33. w.WriteHeader(200)
  34. w.Write(jsonBytes)
  35. }
  36. //-----------------------------------------------------------------------------
  37. // Wraps an HTTP handler, adding error logging.
  38. // If the inner function panics, the outer function recovers, logs, sends an
  39. // HTTP 500 error response.
  40. func RecoverAndLogHandler(handler http.Handler) http.Handler {
  41. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  42. // Wrap the ResponseWriter to remember the status
  43. rww := &ResponseWriterWrapper{-1, w}
  44. begin := time.Now()
  45. // Common headers
  46. origin := r.Header.Get("Origin")
  47. rww.Header().Set("Access-Control-Allow-Origin", origin)
  48. rww.Header().Set("Access-Control-Allow-Credentials", "true")
  49. rww.Header().Set("Access-Control-Expose-Headers", "X-Server-Time")
  50. rww.Header().Set("X-Server-Time", fmt.Sprintf("%v", begin.Unix()))
  51. defer func() {
  52. // Send a 500 error if a panic happens during a handler.
  53. // Without this, Chrome & Firefox were retrying aborted ajax requests,
  54. // at least to my localhost.
  55. if e := recover(); e != nil {
  56. // If RPCResponse
  57. if res, ok := e.(RPCResponse); ok {
  58. WriteRPCResponseHTTP(rww, res)
  59. } else {
  60. // For the rest,
  61. log.Error("Panic in RPC HTTP handler", "error", e, "stack", string(debug.Stack()))
  62. rww.WriteHeader(http.StatusInternalServerError)
  63. WriteRPCResponseHTTP(rww, NewRPCResponse("", nil, Fmt("Internal Server Error: %v", e)))
  64. }
  65. }
  66. // Finally, log.
  67. durationMS := time.Since(begin).Nanoseconds() / 1000000
  68. if rww.Status == -1 {
  69. rww.Status = 200
  70. }
  71. log.Info("Served RPC HTTP response",
  72. "method", r.Method, "url", r.URL,
  73. "status", rww.Status, "duration", durationMS,
  74. "remoteAddr", r.RemoteAddr,
  75. )
  76. }()
  77. handler.ServeHTTP(rww, r)
  78. })
  79. }
  80. // Remember the status for logging
  81. type ResponseWriterWrapper struct {
  82. Status int
  83. http.ResponseWriter
  84. }
  85. func (w *ResponseWriterWrapper) WriteHeader(status int) {
  86. w.Status = status
  87. w.ResponseWriter.WriteHeader(status)
  88. }
  89. // implements http.Hijacker
  90. func (w *ResponseWriterWrapper) Hijack() (net.Conn, *bufio.ReadWriter, error) {
  91. return w.ResponseWriter.(http.Hijacker).Hijack()
  92. }
  93. // Stick it as a deferred statement in gouroutines to prevent the program from crashing.
  94. func Recover(daemonName string) {
  95. if e := recover(); e != nil {
  96. stack := string(debug.Stack())
  97. errorString := fmt.Sprintf("[%s] %s\n%s", daemonName, e, stack)
  98. alert.Alert(errorString)
  99. }
  100. }