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.

121 lines
3.4 KiB

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