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.

155 lines
4.1 KiB

  1. // Commons for HTTP handling
  2. package rpc
  3. import (
  4. "bytes"
  5. "fmt"
  6. "net/http"
  7. "runtime/debug"
  8. "time"
  9. "github.com/tendermint/tendermint/alert"
  10. "github.com/tendermint/tendermint/binary"
  11. . "github.com/tendermint/tendermint/common"
  12. "github.com/tendermint/tendermint/config"
  13. )
  14. func StartHTTPServer() {
  15. initHandlers()
  16. log.Info(Fmt("Starting RPC HTTP server on %s", config.App.GetString("RPC.HTTP.ListenAddr")))
  17. go func() {
  18. log.Crit("RPC HTTPServer stopped", "result", http.ListenAndServe(config.App.GetString("RPC.HTTP.ListenAddr"), RecoverAndLogHandler(http.DefaultServeMux)))
  19. }()
  20. }
  21. //-----------------------------------------------------------------------------
  22. type APIStatus string
  23. const (
  24. API_OK APIStatus = "OK"
  25. API_ERROR APIStatus = "ERROR"
  26. API_INVALID_PARAM APIStatus = "INVALID_PARAM"
  27. API_UNAUTHORIZED APIStatus = "UNAUTHORIZED"
  28. API_REDIRECT APIStatus = "REDIRECT"
  29. )
  30. type APIResponse struct {
  31. Status APIStatus `json:"status"`
  32. Data interface{} `json:"data"`
  33. }
  34. func (res APIResponse) Error() string {
  35. return fmt.Sprintf("Status(%v) %v", res.Status, res.Data)
  36. }
  37. func WriteAPIResponse(w http.ResponseWriter, status APIStatus, data interface{}) {
  38. res := APIResponse{}
  39. res.Status = status
  40. res.Data = data
  41. buf, n, err := new(bytes.Buffer), new(int64), new(error)
  42. binary.WriteJSON(res, buf, n, err)
  43. if *err != nil {
  44. log.Warn("Failed to write JSON APIResponse", "error", err)
  45. }
  46. w.Header().Set("Content-Type", "application/json")
  47. w.WriteHeader(200)
  48. /* Bad idea: (e.g. hard to use with jQuery)
  49. switch res.Status {
  50. case API_OK:
  51. w.WriteHeader(200)
  52. case API_ERROR:
  53. w.WriteHeader(400)
  54. case API_UNAUTHORIZED:
  55. w.WriteHeader(401)
  56. case API_INVALID_PARAM:
  57. w.WriteHeader(420)
  58. case API_REDIRECT:
  59. w.WriteHeader(430)
  60. default:
  61. w.WriteHeader(440)
  62. }*/
  63. w.Write(buf.Bytes())
  64. }
  65. // Wraps an HTTP handler, adding error logging.
  66. //
  67. // If the inner function panics, the outer function recovers, logs, sends an
  68. // HTTP 500 error response.
  69. func RecoverAndLogHandler(handler http.Handler) http.Handler {
  70. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  71. // Wrap the ResponseWriter to remember the status
  72. rww := &ResponseWriterWrapper{-1, w}
  73. begin := time.Now()
  74. // Common headers
  75. rww.Header().Set("Access-Control-Allow-Origin", "*")
  76. /*
  77. origin := r.Header.Get("Origin")
  78. originUrl, err := url.Parse(origin)
  79. if err == nil {
  80. originHost := strings.Split(originUrl.Host, ":")[0]
  81. if strings.HasSuffix(originHost, ".tendermint.com") {
  82. rww.Header().Set("Access-Control-Allow-Origin", origin)
  83. rww.Header().Set("Access-Control-Allow-Credentials", "true")
  84. rww.Header().Set("Access-Control-Expose-Headers", "X-Server-Time")
  85. }
  86. }
  87. */
  88. rww.Header().Set("X-Server-Time", fmt.Sprintf("%v", begin.Unix()))
  89. defer func() {
  90. // Send a 500 error if a panic happens during a handler.
  91. // Without this, Chrome & Firefox were retrying aborted ajax requests,
  92. // at least to my localhost.
  93. if e := recover(); e != nil {
  94. // If APIResponse,
  95. if res, ok := e.(APIResponse); ok {
  96. WriteAPIResponse(rww, res.Status, res.Data)
  97. } else {
  98. // For the rest,
  99. rww.WriteHeader(http.StatusInternalServerError)
  100. rww.Write([]byte("Internal Server Error"))
  101. log.Error("Panic in HTTP handler", "error", e, "stack", string(debug.Stack()))
  102. }
  103. }
  104. // Finally, log.
  105. durationMS := time.Since(begin).Nanoseconds() / 1000000
  106. if rww.Status == -1 {
  107. rww.Status = 200
  108. }
  109. log.Debug("Served HTTP response",
  110. "method", r.Method, "url", r.URL,
  111. "status", rww.Status, "duration", durationMS,
  112. "remoteAddr", r.RemoteAddr,
  113. )
  114. }()
  115. handler.ServeHTTP(rww, r)
  116. })
  117. }
  118. // Remember the status for logging
  119. type ResponseWriterWrapper struct {
  120. Status int
  121. http.ResponseWriter
  122. }
  123. func (w *ResponseWriterWrapper) WriteHeader(status int) {
  124. w.Status = status
  125. w.ResponseWriter.WriteHeader(status)
  126. }
  127. // Stick it as a deferred statement in gouroutines to prevent the program from crashing.
  128. func Recover(daemonName string) {
  129. if e := recover(); e != nil {
  130. stack := string(debug.Stack())
  131. errorString := fmt.Sprintf("[%s] %s\n%s", daemonName, e, stack)
  132. alert.Alert(errorString)
  133. }
  134. }