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