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.

119 lines
3.3 KiB

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