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.

769 lines
23 KiB

8 years ago
8 years ago
7 years ago
8 years ago
8 years ago
8 years ago
7 years ago
7 years ago
7 years ago
8 years ago
7 years ago
7 years ago
8 years ago
8 years ago
8 years ago
8 years ago
new pubsub package comment out failing consensus tests for now rewrite rpc httpclient to use new pubsub package import pubsub as tmpubsub, query as tmquery make event IDs constants EventKey -> EventTypeKey rename EventsPubsub to PubSub mempool does not use pubsub rename eventsSub to pubsub new subscribe API fix channel size issues and consensus tests bugs refactor rpc client add missing discardFromChan method add mutex rename pubsub to eventBus remove IsRunning from WSRPCConnection interface (not needed) add a comment in broadcastNewRoundStepsAndVotes rename registerEventCallbacks to broadcastNewRoundStepsAndVotes See https://dave.cheney.net/2014/03/19/channel-axioms stop eventBuses after reactor tests remove unnecessary Unsubscribe return subscribe helper function move discardFromChan to where it is used subscribe now returns an err this gives us ability to refuse to subscribe if pubsub is at its max capacity. use context for control overflow cache queries handle err when subscribing in replay_test rename testClientID to testSubscriber extract var set channel buffer capacity to 1 in replay_file fix byzantine_test unsubscribe from single event, not all events refactor httpclient to return events to appropriate channels return failing testReplayCrashBeforeWriteVote test fix TestValidatorSetChanges refactor code a bit fix testReplayCrashBeforeWriteVote add comment fix TestValidatorSetChanges fixes from Bucky's review update comment [ci skip] test TxEventBuffer update changelog fix TestValidatorSetChanges (2nd attempt) only do wg.Done when no errors benchmark event bus create pubsub server inside NewEventBus only expose config params (later if needed) set buffer capacity to 0 so we are not testing cache new tx event format: key = "Tx" plus a tag {"tx.hash": XYZ} This should allow to subscribe to all transactions! or a specific one using a query: "tm.events.type = Tx and tx.hash = '013ABF99434...'" use TimeoutCommit instead of afterPublishEventNewBlockTimeout TimeoutCommit is the time a node waits after committing a block, before it goes into the next height. So it will finish everything from the last block, but then wait a bit. The idea is this gives it time to hear more votes from other validators, to strengthen the commit it includes in the next block. But it also gives it time to hear about new transactions. waitForBlockWithUpdatedVals rewrite WAL crash tests Task: test that we can recover from any WAL crash. Solution: the old tests were relying on event hub being run in the same thread (we were injecting the private validator's last signature). when considering a rewrite, we considered two possible solutions: write a "fuzzy" testing system where WAL is crashing upon receiving a new message, or inject failures and trigger them in tests using something like https://github.com/coreos/gofail. remove sleep no cs.Lock around wal.Save test different cases (empty block, non-empty block, ...) comments add comments test 4 cases: empty block, non-empty block, non-empty block with smaller part size, many blocks fixes as per Bucky's last review reset subscriptions on UnsubscribeAll use a simple counter to track message for which we panicked also, set a smaller part size for all test cases
8 years ago
new pubsub package comment out failing consensus tests for now rewrite rpc httpclient to use new pubsub package import pubsub as tmpubsub, query as tmquery make event IDs constants EventKey -> EventTypeKey rename EventsPubsub to PubSub mempool does not use pubsub rename eventsSub to pubsub new subscribe API fix channel size issues and consensus tests bugs refactor rpc client add missing discardFromChan method add mutex rename pubsub to eventBus remove IsRunning from WSRPCConnection interface (not needed) add a comment in broadcastNewRoundStepsAndVotes rename registerEventCallbacks to broadcastNewRoundStepsAndVotes See https://dave.cheney.net/2014/03/19/channel-axioms stop eventBuses after reactor tests remove unnecessary Unsubscribe return subscribe helper function move discardFromChan to where it is used subscribe now returns an err this gives us ability to refuse to subscribe if pubsub is at its max capacity. use context for control overflow cache queries handle err when subscribing in replay_test rename testClientID to testSubscriber extract var set channel buffer capacity to 1 in replay_file fix byzantine_test unsubscribe from single event, not all events refactor httpclient to return events to appropriate channels return failing testReplayCrashBeforeWriteVote test fix TestValidatorSetChanges refactor code a bit fix testReplayCrashBeforeWriteVote add comment fix TestValidatorSetChanges fixes from Bucky's review update comment [ci skip] test TxEventBuffer update changelog fix TestValidatorSetChanges (2nd attempt) only do wg.Done when no errors benchmark event bus create pubsub server inside NewEventBus only expose config params (later if needed) set buffer capacity to 0 so we are not testing cache new tx event format: key = "Tx" plus a tag {"tx.hash": XYZ} This should allow to subscribe to all transactions! or a specific one using a query: "tm.events.type = Tx and tx.hash = '013ABF99434...'" use TimeoutCommit instead of afterPublishEventNewBlockTimeout TimeoutCommit is the time a node waits after committing a block, before it goes into the next height. So it will finish everything from the last block, but then wait a bit. The idea is this gives it time to hear more votes from other validators, to strengthen the commit it includes in the next block. But it also gives it time to hear about new transactions. waitForBlockWithUpdatedVals rewrite WAL crash tests Task: test that we can recover from any WAL crash. Solution: the old tests were relying on event hub being run in the same thread (we were injecting the private validator's last signature). when considering a rewrite, we considered two possible solutions: write a "fuzzy" testing system where WAL is crashing upon receiving a new message, or inject failures and trigger them in tests using something like https://github.com/coreos/gofail. remove sleep no cs.Lock around wal.Save test different cases (empty block, non-empty block, ...) comments add comments test 4 cases: empty block, non-empty block, non-empty block with smaller part size, many blocks fixes as per Bucky's last review reset subscriptions on UnsubscribeAll use a simple counter to track message for which we panicked also, set a smaller part size for all test cases
8 years ago
8 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
new pubsub package comment out failing consensus tests for now rewrite rpc httpclient to use new pubsub package import pubsub as tmpubsub, query as tmquery make event IDs constants EventKey -> EventTypeKey rename EventsPubsub to PubSub mempool does not use pubsub rename eventsSub to pubsub new subscribe API fix channel size issues and consensus tests bugs refactor rpc client add missing discardFromChan method add mutex rename pubsub to eventBus remove IsRunning from WSRPCConnection interface (not needed) add a comment in broadcastNewRoundStepsAndVotes rename registerEventCallbacks to broadcastNewRoundStepsAndVotes See https://dave.cheney.net/2014/03/19/channel-axioms stop eventBuses after reactor tests remove unnecessary Unsubscribe return subscribe helper function move discardFromChan to where it is used subscribe now returns an err this gives us ability to refuse to subscribe if pubsub is at its max capacity. use context for control overflow cache queries handle err when subscribing in replay_test rename testClientID to testSubscriber extract var set channel buffer capacity to 1 in replay_file fix byzantine_test unsubscribe from single event, not all events refactor httpclient to return events to appropriate channels return failing testReplayCrashBeforeWriteVote test fix TestValidatorSetChanges refactor code a bit fix testReplayCrashBeforeWriteVote add comment fix TestValidatorSetChanges fixes from Bucky's review update comment [ci skip] test TxEventBuffer update changelog fix TestValidatorSetChanges (2nd attempt) only do wg.Done when no errors benchmark event bus create pubsub server inside NewEventBus only expose config params (later if needed) set buffer capacity to 0 so we are not testing cache new tx event format: key = "Tx" plus a tag {"tx.hash": XYZ} This should allow to subscribe to all transactions! or a specific one using a query: "tm.events.type = Tx and tx.hash = '013ABF99434...'" use TimeoutCommit instead of afterPublishEventNewBlockTimeout TimeoutCommit is the time a node waits after committing a block, before it goes into the next height. So it will finish everything from the last block, but then wait a bit. The idea is this gives it time to hear more votes from other validators, to strengthen the commit it includes in the next block. But it also gives it time to hear about new transactions. waitForBlockWithUpdatedVals rewrite WAL crash tests Task: test that we can recover from any WAL crash. Solution: the old tests were relying on event hub being run in the same thread (we were injecting the private validator's last signature). when considering a rewrite, we considered two possible solutions: write a "fuzzy" testing system where WAL is crashing upon receiving a new message, or inject failures and trigger them in tests using something like https://github.com/coreos/gofail. remove sleep no cs.Lock around wal.Save test different cases (empty block, non-empty block, ...) comments add comments test 4 cases: empty block, non-empty block, non-empty block with smaller part size, many blocks fixes as per Bucky's last review reset subscriptions on UnsubscribeAll use a simple counter to track message for which we panicked also, set a smaller part size for all test cases
8 years ago
7 years ago
8 years ago
7 years ago
new pubsub package comment out failing consensus tests for now rewrite rpc httpclient to use new pubsub package import pubsub as tmpubsub, query as tmquery make event IDs constants EventKey -> EventTypeKey rename EventsPubsub to PubSub mempool does not use pubsub rename eventsSub to pubsub new subscribe API fix channel size issues and consensus tests bugs refactor rpc client add missing discardFromChan method add mutex rename pubsub to eventBus remove IsRunning from WSRPCConnection interface (not needed) add a comment in broadcastNewRoundStepsAndVotes rename registerEventCallbacks to broadcastNewRoundStepsAndVotes See https://dave.cheney.net/2014/03/19/channel-axioms stop eventBuses after reactor tests remove unnecessary Unsubscribe return subscribe helper function move discardFromChan to where it is used subscribe now returns an err this gives us ability to refuse to subscribe if pubsub is at its max capacity. use context for control overflow cache queries handle err when subscribing in replay_test rename testClientID to testSubscriber extract var set channel buffer capacity to 1 in replay_file fix byzantine_test unsubscribe from single event, not all events refactor httpclient to return events to appropriate channels return failing testReplayCrashBeforeWriteVote test fix TestValidatorSetChanges refactor code a bit fix testReplayCrashBeforeWriteVote add comment fix TestValidatorSetChanges fixes from Bucky's review update comment [ci skip] test TxEventBuffer update changelog fix TestValidatorSetChanges (2nd attempt) only do wg.Done when no errors benchmark event bus create pubsub server inside NewEventBus only expose config params (later if needed) set buffer capacity to 0 so we are not testing cache new tx event format: key = "Tx" plus a tag {"tx.hash": XYZ} This should allow to subscribe to all transactions! or a specific one using a query: "tm.events.type = Tx and tx.hash = '013ABF99434...'" use TimeoutCommit instead of afterPublishEventNewBlockTimeout TimeoutCommit is the time a node waits after committing a block, before it goes into the next height. So it will finish everything from the last block, but then wait a bit. The idea is this gives it time to hear more votes from other validators, to strengthen the commit it includes in the next block. But it also gives it time to hear about new transactions. waitForBlockWithUpdatedVals rewrite WAL crash tests Task: test that we can recover from any WAL crash. Solution: the old tests were relying on event hub being run in the same thread (we were injecting the private validator's last signature). when considering a rewrite, we considered two possible solutions: write a "fuzzy" testing system where WAL is crashing upon receiving a new message, or inject failures and trigger them in tests using something like https://github.com/coreos/gofail. remove sleep no cs.Lock around wal.Save test different cases (empty block, non-empty block, ...) comments add comments test 4 cases: empty block, non-empty block, non-empty block with smaller part size, many blocks fixes as per Bucky's last review reset subscriptions on UnsubscribeAll use a simple counter to track message for which we panicked also, set a smaller part size for all test cases
8 years ago
8 years ago
  1. package rpcserver
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/hex"
  6. "encoding/json"
  7. "fmt"
  8. "io/ioutil"
  9. "net/http"
  10. "reflect"
  11. "runtime/debug"
  12. "sort"
  13. "strings"
  14. "time"
  15. "github.com/gorilla/websocket"
  16. "github.com/pkg/errors"
  17. types "github.com/tendermint/tendermint/rpc/lib/types"
  18. cmn "github.com/tendermint/tmlibs/common"
  19. "github.com/tendermint/tmlibs/log"
  20. )
  21. // RegisterRPCFuncs adds a route for each function in the funcMap, as well as general jsonrpc and websocket handlers for all functions.
  22. // "result" is the interface on which the result objects are registered, and is popualted with every RPCResponse
  23. func RegisterRPCFuncs(mux *http.ServeMux, funcMap map[string]*RPCFunc, logger log.Logger) {
  24. // HTTP endpoints
  25. for funcName, rpcFunc := range funcMap {
  26. mux.HandleFunc("/"+funcName, makeHTTPHandler(rpcFunc, logger))
  27. }
  28. // JSONRPC endpoints
  29. mux.HandleFunc("/", makeJSONRPCHandler(funcMap, logger))
  30. }
  31. //-------------------------------------
  32. // function introspection
  33. // RPCFunc contains the introspected type information for a function
  34. type RPCFunc struct {
  35. f reflect.Value // underlying rpc function
  36. args []reflect.Type // type of each function arg
  37. returns []reflect.Type // type of each return arg
  38. argNames []string // name of each argument
  39. ws bool // websocket only
  40. }
  41. // NewRPCFunc wraps a function for introspection.
  42. // f is the function, args are comma separated argument names
  43. func NewRPCFunc(f interface{}, args string) *RPCFunc {
  44. return newRPCFunc(f, args, false)
  45. }
  46. // NewWSRPCFunc wraps a function for introspection and use in the websockets.
  47. func NewWSRPCFunc(f interface{}, args string) *RPCFunc {
  48. return newRPCFunc(f, args, true)
  49. }
  50. func newRPCFunc(f interface{}, args string, ws bool) *RPCFunc {
  51. var argNames []string
  52. if args != "" {
  53. argNames = strings.Split(args, ",")
  54. }
  55. return &RPCFunc{
  56. f: reflect.ValueOf(f),
  57. args: funcArgTypes(f),
  58. returns: funcReturnTypes(f),
  59. argNames: argNames,
  60. ws: ws,
  61. }
  62. }
  63. // return a function's argument types
  64. func funcArgTypes(f interface{}) []reflect.Type {
  65. t := reflect.TypeOf(f)
  66. n := t.NumIn()
  67. typez := make([]reflect.Type, n)
  68. for i := 0; i < n; i++ {
  69. typez[i] = t.In(i)
  70. }
  71. return typez
  72. }
  73. // return a function's return types
  74. func funcReturnTypes(f interface{}) []reflect.Type {
  75. t := reflect.TypeOf(f)
  76. n := t.NumOut()
  77. typez := make([]reflect.Type, n)
  78. for i := 0; i < n; i++ {
  79. typez[i] = t.Out(i)
  80. }
  81. return typez
  82. }
  83. // function introspection
  84. //-----------------------------------------------------------------------------
  85. // rpc.json
  86. // jsonrpc calls grab the given method's function info and runs reflect.Call
  87. func makeJSONRPCHandler(funcMap map[string]*RPCFunc, logger log.Logger) http.HandlerFunc {
  88. return func(w http.ResponseWriter, r *http.Request) {
  89. b, err := ioutil.ReadAll(r.Body)
  90. if err != nil {
  91. WriteRPCResponseHTTP(w, types.RPCInvalidRequestError("", errors.Wrap(err, "Error reading request body")))
  92. return
  93. }
  94. // if its an empty request (like from a browser),
  95. // just display a list of functions
  96. if len(b) == 0 {
  97. writeListOfEndpoints(w, r, funcMap)
  98. return
  99. }
  100. var request types.RPCRequest
  101. err = json.Unmarshal(b, &request)
  102. if err != nil {
  103. WriteRPCResponseHTTP(w, types.RPCParseError("", errors.Wrap(err, "Error unmarshalling request")))
  104. return
  105. }
  106. // A Notification is a Request object without an "id" member.
  107. // The Server MUST NOT reply to a Notification, including those that are within a batch request.
  108. if request.ID == "" {
  109. logger.Debug("HTTPJSONRPC received a notification, skipping... (please send a non-empty ID if you want to call a method)")
  110. return
  111. }
  112. if len(r.URL.Path) > 1 {
  113. WriteRPCResponseHTTP(w, types.RPCInvalidRequestError(request.ID, errors.Errorf("Path %s is invalid", r.URL.Path)))
  114. return
  115. }
  116. rpcFunc := funcMap[request.Method]
  117. if rpcFunc == nil || rpcFunc.ws {
  118. WriteRPCResponseHTTP(w, types.RPCMethodNotFoundError(request.ID))
  119. return
  120. }
  121. var args []reflect.Value
  122. if len(request.Params) > 0 {
  123. args, err = jsonParamsToArgsRPC(rpcFunc, request.Params)
  124. if err != nil {
  125. WriteRPCResponseHTTP(w, types.RPCInvalidParamsError(request.ID, errors.Wrap(err, "Error converting json params to arguments")))
  126. return
  127. }
  128. }
  129. returns := rpcFunc.f.Call(args)
  130. logger.Info("HTTPJSONRPC", "method", request.Method, "args", args, "returns", returns)
  131. result, err := unreflectResult(returns)
  132. if err != nil {
  133. WriteRPCResponseHTTP(w, types.RPCInternalError(request.ID, err))
  134. return
  135. }
  136. WriteRPCResponseHTTP(w, types.NewRPCSuccessResponse(request.ID, result))
  137. }
  138. }
  139. func mapParamsToArgs(rpcFunc *RPCFunc, params map[string]*json.RawMessage, argsOffset int) ([]reflect.Value, error) {
  140. values := make([]reflect.Value, len(rpcFunc.argNames))
  141. for i, argName := range rpcFunc.argNames {
  142. argType := rpcFunc.args[i+argsOffset]
  143. if p, ok := params[argName]; ok && p != nil && len(*p) > 0 {
  144. val := reflect.New(argType)
  145. err := json.Unmarshal(*p, val.Interface())
  146. if err != nil {
  147. return nil, err
  148. }
  149. values[i] = val.Elem()
  150. } else { // use default for that type
  151. values[i] = reflect.Zero(argType)
  152. }
  153. }
  154. return values, nil
  155. }
  156. func arrayParamsToArgs(rpcFunc *RPCFunc, params []*json.RawMessage, argsOffset int) ([]reflect.Value, error) {
  157. if len(rpcFunc.argNames) != len(params) {
  158. return nil, errors.Errorf("Expected %v parameters (%v), got %v (%v)",
  159. len(rpcFunc.argNames), rpcFunc.argNames, len(params), params)
  160. }
  161. values := make([]reflect.Value, len(params))
  162. for i, p := range params {
  163. argType := rpcFunc.args[i+argsOffset]
  164. val := reflect.New(argType)
  165. err := json.Unmarshal(*p, val.Interface())
  166. if err != nil {
  167. return nil, err
  168. }
  169. values[i] = val.Elem()
  170. }
  171. return values, nil
  172. }
  173. // raw is unparsed json (from json.RawMessage) encoding either a map or an array.
  174. //
  175. // argsOffset should be 0 for RPC calls, and 1 for WS requests, where len(rpcFunc.args) != len(rpcFunc.argNames).
  176. // Example:
  177. // rpcFunc.args = [rpctypes.WSRPCContext string]
  178. // rpcFunc.argNames = ["arg"]
  179. func jsonParamsToArgs(rpcFunc *RPCFunc, raw []byte, argsOffset int) ([]reflect.Value, error) {
  180. // first, try to get the map..
  181. var m map[string]*json.RawMessage
  182. err := json.Unmarshal(raw, &m)
  183. if err == nil {
  184. return mapParamsToArgs(rpcFunc, m, argsOffset)
  185. }
  186. // otherwise, try an array
  187. var a []*json.RawMessage
  188. err = json.Unmarshal(raw, &a)
  189. if err == nil {
  190. return arrayParamsToArgs(rpcFunc, a, argsOffset)
  191. }
  192. // otherwise, bad format, we cannot parse
  193. return nil, errors.Errorf("Unknown type for JSON params: %v. Expected map or array", err)
  194. }
  195. // Convert a []interface{} OR a map[string]interface{} to properly typed values
  196. func jsonParamsToArgsRPC(rpcFunc *RPCFunc, params json.RawMessage) ([]reflect.Value, error) {
  197. return jsonParamsToArgs(rpcFunc, params, 0)
  198. }
  199. // Same as above, but with the first param the websocket connection
  200. func jsonParamsToArgsWS(rpcFunc *RPCFunc, params json.RawMessage, wsCtx types.WSRPCContext) ([]reflect.Value, error) {
  201. values, err := jsonParamsToArgs(rpcFunc, params, 1)
  202. if err != nil {
  203. return nil, err
  204. }
  205. return append([]reflect.Value{reflect.ValueOf(wsCtx)}, values...), nil
  206. }
  207. // rpc.json
  208. //-----------------------------------------------------------------------------
  209. // rpc.http
  210. // convert from a function name to the http handler
  211. func makeHTTPHandler(rpcFunc *RPCFunc, logger log.Logger) func(http.ResponseWriter, *http.Request) {
  212. // Exception for websocket endpoints
  213. if rpcFunc.ws {
  214. return func(w http.ResponseWriter, r *http.Request) {
  215. WriteRPCResponseHTTP(w, types.RPCMethodNotFoundError(""))
  216. }
  217. }
  218. // All other endpoints
  219. return func(w http.ResponseWriter, r *http.Request) {
  220. logger.Debug("HTTP HANDLER", "req", r)
  221. args, err := httpParamsToArgs(rpcFunc, r)
  222. if err != nil {
  223. WriteRPCResponseHTTP(w, types.RPCInvalidParamsError("", errors.Wrap(err, "Error converting http params to arguments")))
  224. return
  225. }
  226. returns := rpcFunc.f.Call(args)
  227. logger.Info("HTTPRestRPC", "method", r.URL.Path, "args", args, "returns", returns)
  228. result, err := unreflectResult(returns)
  229. if err != nil {
  230. WriteRPCResponseHTTP(w, types.RPCInternalError("", err))
  231. return
  232. }
  233. WriteRPCResponseHTTP(w, types.NewRPCSuccessResponse("", result))
  234. }
  235. }
  236. // Covert an http query to a list of properly typed values.
  237. // To be properly decoded the arg must be a concrete type from tendermint (if its an interface).
  238. func httpParamsToArgs(rpcFunc *RPCFunc, r *http.Request) ([]reflect.Value, error) {
  239. values := make([]reflect.Value, len(rpcFunc.args))
  240. for i, name := range rpcFunc.argNames {
  241. argType := rpcFunc.args[i]
  242. values[i] = reflect.Zero(argType) // set default for that type
  243. arg := GetParam(r, name)
  244. // log.Notice("param to arg", "argType", argType, "name", name, "arg", arg)
  245. if "" == arg {
  246. continue
  247. }
  248. v, err, ok := nonJsonToArg(argType, arg)
  249. if err != nil {
  250. return nil, err
  251. }
  252. if ok {
  253. values[i] = v
  254. continue
  255. }
  256. values[i], err = _jsonStringToArg(argType, arg)
  257. if err != nil {
  258. return nil, err
  259. }
  260. }
  261. return values, nil
  262. }
  263. func _jsonStringToArg(ty reflect.Type, arg string) (reflect.Value, error) {
  264. v := reflect.New(ty)
  265. err := json.Unmarshal([]byte(arg), v.Interface())
  266. if err != nil {
  267. return v, err
  268. }
  269. v = v.Elem()
  270. return v, nil
  271. }
  272. func nonJsonToArg(ty reflect.Type, arg string) (reflect.Value, error, bool) {
  273. isQuotedString := strings.HasPrefix(arg, `"`) && strings.HasSuffix(arg, `"`)
  274. isHexString := strings.HasPrefix(strings.ToLower(arg), "0x")
  275. expectingString := ty.Kind() == reflect.String
  276. expectingByteSlice := ty.Kind() == reflect.Slice && ty.Elem().Kind() == reflect.Uint8
  277. if isHexString {
  278. if !expectingString && !expectingByteSlice {
  279. err := errors.Errorf("Got a hex string arg, but expected '%s'",
  280. ty.Kind().String())
  281. return reflect.ValueOf(nil), err, false
  282. }
  283. var value []byte
  284. value, err := hex.DecodeString(arg[2:])
  285. if err != nil {
  286. return reflect.ValueOf(nil), err, false
  287. }
  288. if ty.Kind() == reflect.String {
  289. return reflect.ValueOf(string(value)), nil, true
  290. }
  291. return reflect.ValueOf([]byte(value)), nil, true
  292. }
  293. if isQuotedString && expectingByteSlice {
  294. v := reflect.New(reflect.TypeOf(""))
  295. err := json.Unmarshal([]byte(arg), v.Interface())
  296. if err != nil {
  297. return reflect.ValueOf(nil), err, false
  298. }
  299. v = v.Elem()
  300. return reflect.ValueOf([]byte(v.String())), nil, true
  301. }
  302. return reflect.ValueOf(nil), nil, false
  303. }
  304. // rpc.http
  305. //-----------------------------------------------------------------------------
  306. // rpc.websocket
  307. const (
  308. defaultWSWriteChanCapacity = 1000
  309. defaultWSWriteWait = 10 * time.Second
  310. defaultWSReadWait = 30 * time.Second
  311. defaultWSPingPeriod = (defaultWSReadWait * 9) / 10
  312. )
  313. // a single websocket connection contains listener id, underlying ws
  314. // connection, and the event switch for subscribing to events.
  315. //
  316. // In case of an error, the connection is stopped.
  317. type wsConnection struct {
  318. cmn.BaseService
  319. remoteAddr string
  320. baseConn *websocket.Conn
  321. writeChan chan types.RPCResponse
  322. funcMap map[string]*RPCFunc
  323. // write channel capacity
  324. writeChanCapacity int
  325. // each write times out after this.
  326. writeWait time.Duration
  327. // Connection times out if we haven't received *anything* in this long, not even pings.
  328. readWait time.Duration
  329. // Send pings to server with this period. Must be less than readWait, but greater than zero.
  330. pingPeriod time.Duration
  331. // object that is used to subscribe / unsubscribe from events
  332. eventSub types.EventSubscriber
  333. }
  334. // NewWSConnection wraps websocket.Conn.
  335. //
  336. // See the commentary on the func(*wsConnection) functions for a detailed
  337. // description of how to configure ping period and pong wait time. NOTE: if the
  338. // write buffer is full, pongs may be dropped, which may cause clients to
  339. // disconnect. see https://github.com/gorilla/websocket/issues/97
  340. func NewWSConnection(baseConn *websocket.Conn, funcMap map[string]*RPCFunc, options ...func(*wsConnection)) *wsConnection {
  341. wsc := &wsConnection{
  342. remoteAddr: baseConn.RemoteAddr().String(),
  343. baseConn: baseConn,
  344. funcMap: funcMap,
  345. writeWait: defaultWSWriteWait,
  346. writeChanCapacity: defaultWSWriteChanCapacity,
  347. readWait: defaultWSReadWait,
  348. pingPeriod: defaultWSPingPeriod,
  349. }
  350. for _, option := range options {
  351. option(wsc)
  352. }
  353. wsc.BaseService = *cmn.NewBaseService(nil, "wsConnection", wsc)
  354. return wsc
  355. }
  356. // EventSubscriber sets object that is used to subscribe / unsubscribe from
  357. // events - not Goroutine-safe. If none given, default node's eventBus will be
  358. // used.
  359. func EventSubscriber(eventSub types.EventSubscriber) func(*wsConnection) {
  360. return func(wsc *wsConnection) {
  361. wsc.eventSub = eventSub
  362. }
  363. }
  364. // WriteWait sets the amount of time to wait before a websocket write times out.
  365. // It should only be used in the constructor - not Goroutine-safe.
  366. func WriteWait(writeWait time.Duration) func(*wsConnection) {
  367. return func(wsc *wsConnection) {
  368. wsc.writeWait = writeWait
  369. }
  370. }
  371. // WriteChanCapacity sets the capacity of the websocket write channel.
  372. // It should only be used in the constructor - not Goroutine-safe.
  373. func WriteChanCapacity(cap int) func(*wsConnection) {
  374. return func(wsc *wsConnection) {
  375. wsc.writeChanCapacity = cap
  376. }
  377. }
  378. // ReadWait sets the amount of time to wait before a websocket read times out.
  379. // It should only be used in the constructor - not Goroutine-safe.
  380. func ReadWait(readWait time.Duration) func(*wsConnection) {
  381. return func(wsc *wsConnection) {
  382. wsc.readWait = readWait
  383. }
  384. }
  385. // PingPeriod sets the duration for sending websocket pings.
  386. // It should only be used in the constructor - not Goroutine-safe.
  387. func PingPeriod(pingPeriod time.Duration) func(*wsConnection) {
  388. return func(wsc *wsConnection) {
  389. wsc.pingPeriod = pingPeriod
  390. }
  391. }
  392. // OnStart implements cmn.Service by starting the read and write routines. It
  393. // blocks until the connection closes.
  394. func (wsc *wsConnection) OnStart() error {
  395. wsc.writeChan = make(chan types.RPCResponse, wsc.writeChanCapacity)
  396. // Read subscriptions/unsubscriptions to events
  397. go wsc.readRoutine()
  398. // Write responses, BLOCKING.
  399. wsc.writeRoutine()
  400. return nil
  401. }
  402. // OnStop implements cmn.Service by unsubscribing remoteAddr from all subscriptions.
  403. func (wsc *wsConnection) OnStop() {
  404. // Both read and write loops close the websocket connection when they exit their loops.
  405. // The writeChan is never closed, to allow WriteRPCResponse() to fail.
  406. if wsc.eventSub != nil {
  407. wsc.eventSub.UnsubscribeAll(context.TODO(), wsc.remoteAddr)
  408. }
  409. }
  410. // GetRemoteAddr returns the remote address of the underlying connection.
  411. // It implements WSRPCConnection
  412. func (wsc *wsConnection) GetRemoteAddr() string {
  413. return wsc.remoteAddr
  414. }
  415. // GetEventSubscriber implements WSRPCConnection by returning event subscriber.
  416. func (wsc *wsConnection) GetEventSubscriber() types.EventSubscriber {
  417. return wsc.eventSub
  418. }
  419. // WriteRPCResponse pushes a response to the writeChan, and blocks until it is accepted.
  420. // It implements WSRPCConnection. It is Goroutine-safe.
  421. func (wsc *wsConnection) WriteRPCResponse(resp types.RPCResponse) {
  422. select {
  423. case <-wsc.Quit():
  424. return
  425. case wsc.writeChan <- resp:
  426. }
  427. }
  428. // TryWriteRPCResponse attempts to push a response to the writeChan, but does not block.
  429. // It implements WSRPCConnection. It is Goroutine-safe
  430. func (wsc *wsConnection) TryWriteRPCResponse(resp types.RPCResponse) bool {
  431. select {
  432. case <-wsc.Quit():
  433. return false
  434. case wsc.writeChan <- resp:
  435. return true
  436. default:
  437. return false
  438. }
  439. }
  440. // Read from the socket and subscribe to or unsubscribe from events
  441. func (wsc *wsConnection) readRoutine() {
  442. defer func() {
  443. if r := recover(); r != nil {
  444. err, ok := r.(error)
  445. if !ok {
  446. err = fmt.Errorf("WSJSONRPC: %v", r)
  447. }
  448. wsc.Logger.Error("Panic in WSJSONRPC handler", "err", err, "stack", string(debug.Stack()))
  449. wsc.WriteRPCResponse(types.RPCInternalError("unknown", err))
  450. go wsc.readRoutine()
  451. } else {
  452. wsc.baseConn.Close() // nolint: errcheck
  453. }
  454. }()
  455. wsc.baseConn.SetPongHandler(func(m string) error {
  456. return wsc.baseConn.SetReadDeadline(time.Now().Add(wsc.readWait))
  457. })
  458. for {
  459. select {
  460. case <-wsc.Quit():
  461. return
  462. default:
  463. // reset deadline for every type of message (control or data)
  464. if err := wsc.baseConn.SetReadDeadline(time.Now().Add(wsc.readWait)); err != nil {
  465. wsc.Logger.Error("failed to set read deadline", "err", err)
  466. }
  467. var in []byte
  468. _, in, err := wsc.baseConn.ReadMessage()
  469. if err != nil {
  470. if websocket.IsCloseError(err, websocket.CloseNormalClosure) {
  471. wsc.Logger.Info("Client closed the connection")
  472. } else {
  473. wsc.Logger.Error("Failed to read request", "err", err)
  474. }
  475. wsc.Stop()
  476. return
  477. }
  478. var request types.RPCRequest
  479. err = json.Unmarshal(in, &request)
  480. if err != nil {
  481. wsc.WriteRPCResponse(types.RPCParseError("", errors.Wrap(err, "Error unmarshaling request")))
  482. continue
  483. }
  484. // A Notification is a Request object without an "id" member.
  485. // The Server MUST NOT reply to a Notification, including those that are within a batch request.
  486. if request.ID == "" {
  487. wsc.Logger.Debug("WSJSONRPC received a notification, skipping... (please send a non-empty ID if you want to call a method)")
  488. continue
  489. }
  490. // Now, fetch the RPCFunc and execute it.
  491. rpcFunc := wsc.funcMap[request.Method]
  492. if rpcFunc == nil {
  493. wsc.WriteRPCResponse(types.RPCMethodNotFoundError(request.ID))
  494. continue
  495. }
  496. var args []reflect.Value
  497. if rpcFunc.ws {
  498. wsCtx := types.WSRPCContext{Request: request, WSRPCConnection: wsc}
  499. if len(request.Params) > 0 {
  500. args, err = jsonParamsToArgsWS(rpcFunc, request.Params, wsCtx)
  501. }
  502. } else {
  503. if len(request.Params) > 0 {
  504. args, err = jsonParamsToArgsRPC(rpcFunc, request.Params)
  505. }
  506. }
  507. if err != nil {
  508. wsc.WriteRPCResponse(types.RPCInternalError(request.ID, errors.Wrap(err, "Error converting json params to arguments")))
  509. continue
  510. }
  511. returns := rpcFunc.f.Call(args)
  512. // TODO: Need to encode args/returns to string if we want to log them
  513. wsc.Logger.Info("WSJSONRPC", "method", request.Method)
  514. result, err := unreflectResult(returns)
  515. if err != nil {
  516. wsc.WriteRPCResponse(types.RPCInternalError(request.ID, err))
  517. continue
  518. } else {
  519. wsc.WriteRPCResponse(types.NewRPCSuccessResponse(request.ID, result))
  520. continue
  521. }
  522. }
  523. }
  524. }
  525. // receives on a write channel and writes out on the socket
  526. func (wsc *wsConnection) writeRoutine() {
  527. pingTicker := time.NewTicker(wsc.pingPeriod)
  528. defer func() {
  529. pingTicker.Stop()
  530. if err := wsc.baseConn.Close(); err != nil {
  531. wsc.Logger.Error("Error closing connection", "err", err)
  532. }
  533. }()
  534. // https://github.com/gorilla/websocket/issues/97
  535. pongs := make(chan string, 1)
  536. wsc.baseConn.SetPingHandler(func(m string) error {
  537. select {
  538. case pongs <- m:
  539. default:
  540. }
  541. return nil
  542. })
  543. for {
  544. select {
  545. case m := <-pongs:
  546. err := wsc.writeMessageWithDeadline(websocket.PongMessage, []byte(m))
  547. if err != nil {
  548. wsc.Logger.Info("Failed to write pong (client may disconnect)", "err", err)
  549. }
  550. case <-pingTicker.C:
  551. err := wsc.writeMessageWithDeadline(websocket.PingMessage, []byte{})
  552. if err != nil {
  553. wsc.Logger.Error("Failed to write ping", "err", err)
  554. wsc.Stop()
  555. return
  556. }
  557. case msg := <-wsc.writeChan:
  558. jsonBytes, err := json.MarshalIndent(msg, "", " ")
  559. if err != nil {
  560. wsc.Logger.Error("Failed to marshal RPCResponse to JSON", "err", err)
  561. } else {
  562. if err = wsc.writeMessageWithDeadline(websocket.TextMessage, jsonBytes); err != nil {
  563. wsc.Logger.Error("Failed to write response", "err", err)
  564. wsc.Stop()
  565. return
  566. }
  567. }
  568. case <-wsc.Quit():
  569. return
  570. }
  571. }
  572. }
  573. // All writes to the websocket must (re)set the write deadline.
  574. // If some writes don't set it while others do, they may timeout incorrectly (https://github.com/tendermint/tendermint/issues/553)
  575. func (wsc *wsConnection) writeMessageWithDeadline(msgType int, msg []byte) error {
  576. if err := wsc.baseConn.SetWriteDeadline(time.Now().Add(wsc.writeWait)); err != nil {
  577. return err
  578. }
  579. return wsc.baseConn.WriteMessage(msgType, msg)
  580. }
  581. //----------------------------------------
  582. // WebsocketManager is the main manager for all websocket connections.
  583. // It holds the event switch and a map of functions for routing.
  584. // NOTE: The websocket path is defined externally, e.g. in node/node.go
  585. type WebsocketManager struct {
  586. websocket.Upgrader
  587. funcMap map[string]*RPCFunc
  588. logger log.Logger
  589. wsConnOptions []func(*wsConnection)
  590. }
  591. // NewWebsocketManager returns a new WebsocketManager that routes according to
  592. // the given funcMap and connects to the server with the given connection
  593. // options.
  594. func NewWebsocketManager(funcMap map[string]*RPCFunc, wsConnOptions ...func(*wsConnection)) *WebsocketManager {
  595. return &WebsocketManager{
  596. funcMap: funcMap,
  597. Upgrader: websocket.Upgrader{
  598. CheckOrigin: func(r *http.Request) bool {
  599. // TODO ???
  600. return true
  601. },
  602. },
  603. logger: log.NewNopLogger(),
  604. wsConnOptions: wsConnOptions,
  605. }
  606. }
  607. // SetLogger sets the logger.
  608. func (wm *WebsocketManager) SetLogger(l log.Logger) {
  609. wm.logger = l
  610. }
  611. // WebsocketHandler upgrades the request/response (via http.Hijack) and starts the wsConnection.
  612. func (wm *WebsocketManager) WebsocketHandler(w http.ResponseWriter, r *http.Request) {
  613. wsConn, err := wm.Upgrade(w, r, nil)
  614. if err != nil {
  615. // TODO - return http error
  616. wm.logger.Error("Failed to upgrade to websocket connection", "err", err)
  617. return
  618. }
  619. // register connection
  620. con := NewWSConnection(wsConn, wm.funcMap, wm.wsConnOptions...)
  621. con.SetLogger(wm.logger.With("remote", wsConn.RemoteAddr()))
  622. wm.logger.Info("New websocket connection", "remote", con.remoteAddr)
  623. err = con.Start() // Blocking
  624. if err != nil {
  625. wm.logger.Error("Error starting connection", "err", err)
  626. }
  627. }
  628. // rpc.websocket
  629. //-----------------------------------------------------------------------------
  630. // NOTE: assume returns is result struct and error. If error is not nil, return it
  631. func unreflectResult(returns []reflect.Value) (interface{}, error) {
  632. errV := returns[1]
  633. if errV.Interface() != nil {
  634. return nil, errors.Errorf("%v", errV.Interface())
  635. }
  636. rv := returns[0]
  637. // the result is a registered interface,
  638. // we need a pointer to it so we can marshal with type byte
  639. rvp := reflect.New(rv.Type())
  640. rvp.Elem().Set(rv)
  641. return rvp.Interface(), nil
  642. }
  643. // writes a list of available rpc endpoints as an html page
  644. func writeListOfEndpoints(w http.ResponseWriter, r *http.Request, funcMap map[string]*RPCFunc) {
  645. noArgNames := []string{}
  646. argNames := []string{}
  647. for name, funcData := range funcMap {
  648. if len(funcData.args) == 0 {
  649. noArgNames = append(noArgNames, name)
  650. } else {
  651. argNames = append(argNames, name)
  652. }
  653. }
  654. sort.Strings(noArgNames)
  655. sort.Strings(argNames)
  656. buf := new(bytes.Buffer)
  657. buf.WriteString("<html><body>")
  658. buf.WriteString("<br>Available endpoints:<br>")
  659. for _, name := range noArgNames {
  660. link := fmt.Sprintf("http://%s/%s", r.Host, name)
  661. buf.WriteString(fmt.Sprintf("<a href=\"%s\">%s</a></br>", link, link))
  662. }
  663. buf.WriteString("<br>Endpoints that require arguments:<br>")
  664. for _, name := range argNames {
  665. link := fmt.Sprintf("http://%s/%s?", r.Host, name)
  666. funcData := funcMap[name]
  667. for i, argName := range funcData.argNames {
  668. link += argName + "=_"
  669. if i < len(funcData.argNames)-1 {
  670. link += "&"
  671. }
  672. }
  673. buf.WriteString(fmt.Sprintf("<a href=\"%s\">%s</a></br>", link, link))
  674. }
  675. buf.WriteString("</body></html>")
  676. w.Header().Set("Content-Type", "text/html")
  677. w.WriteHeader(200)
  678. w.Write(buf.Bytes()) // nolint: errcheck
  679. }