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.

838 lines
25 KiB

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
7 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
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
8 years ago
7 years ago
8 years ago
7 years ago
7 years ago
6 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
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
7 years ago
7 years ago
7 years ago
7 years ago
8 years ago
7 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. amino "github.com/tendermint/go-amino"
  18. cmn "github.com/tendermint/tendermint/libs/common"
  19. "github.com/tendermint/tendermint/libs/log"
  20. types "github.com/tendermint/tendermint/rpc/lib/types"
  21. )
  22. // RegisterRPCFuncs adds a route for each function in the funcMap, as well as general jsonrpc and websocket handlers for all functions.
  23. // "result" is the interface on which the result objects are registered, and is popualted with every RPCResponse
  24. func RegisterRPCFuncs(mux *http.ServeMux, funcMap map[string]*RPCFunc, cdc *amino.Codec, logger log.Logger) {
  25. // HTTP endpoints
  26. for funcName, rpcFunc := range funcMap {
  27. mux.HandleFunc("/"+funcName, makeHTTPHandler(rpcFunc, cdc, logger))
  28. }
  29. // JSONRPC endpoints
  30. mux.HandleFunc("/", handleInvalidJSONRPCPaths(makeJSONRPCHandler(funcMap, cdc, logger)))
  31. }
  32. //-------------------------------------
  33. // function introspection
  34. // RPCFunc contains the introspected type information for a function
  35. type RPCFunc struct {
  36. f reflect.Value // underlying rpc function
  37. args []reflect.Type // type of each function arg
  38. returns []reflect.Type // type of each return arg
  39. argNames []string // name of each argument
  40. ws bool // websocket only
  41. }
  42. // NewRPCFunc wraps a function for introspection.
  43. // f is the function, args are comma separated argument names
  44. func NewRPCFunc(f interface{}, args string) *RPCFunc {
  45. return newRPCFunc(f, args, false)
  46. }
  47. // NewWSRPCFunc wraps a function for introspection and use in the websockets.
  48. func NewWSRPCFunc(f interface{}, args string) *RPCFunc {
  49. return newRPCFunc(f, args, true)
  50. }
  51. func newRPCFunc(f interface{}, args string, ws bool) *RPCFunc {
  52. var argNames []string
  53. if args != "" {
  54. argNames = strings.Split(args, ",")
  55. }
  56. return &RPCFunc{
  57. f: reflect.ValueOf(f),
  58. args: funcArgTypes(f),
  59. returns: funcReturnTypes(f),
  60. argNames: argNames,
  61. ws: ws,
  62. }
  63. }
  64. // return a function's argument types
  65. func funcArgTypes(f interface{}) []reflect.Type {
  66. t := reflect.TypeOf(f)
  67. n := t.NumIn()
  68. typez := make([]reflect.Type, n)
  69. for i := 0; i < n; i++ {
  70. typez[i] = t.In(i)
  71. }
  72. return typez
  73. }
  74. // return a function's return types
  75. func funcReturnTypes(f interface{}) []reflect.Type {
  76. t := reflect.TypeOf(f)
  77. n := t.NumOut()
  78. typez := make([]reflect.Type, n)
  79. for i := 0; i < n; i++ {
  80. typez[i] = t.Out(i)
  81. }
  82. return typez
  83. }
  84. // function introspection
  85. //-----------------------------------------------------------------------------
  86. // rpc.json
  87. // jsonrpc calls grab the given method's function info and runs reflect.Call
  88. func makeJSONRPCHandler(funcMap map[string]*RPCFunc, cdc *amino.Codec, logger log.Logger) http.HandlerFunc {
  89. return func(w http.ResponseWriter, r *http.Request) {
  90. b, err := ioutil.ReadAll(r.Body)
  91. if err != nil {
  92. WriteRPCResponseHTTP(w, types.RPCInvalidRequestError("", errors.Wrap(err, "Error reading request body")))
  93. return
  94. }
  95. // if its an empty request (like from a browser),
  96. // just display a list of functions
  97. if len(b) == 0 {
  98. writeListOfEndpoints(w, r, funcMap)
  99. return
  100. }
  101. var request types.RPCRequest
  102. err = json.Unmarshal(b, &request)
  103. if err != nil {
  104. WriteRPCResponseHTTP(w, types.RPCParseError("", errors.Wrap(err, "Error unmarshalling request")))
  105. return
  106. }
  107. // A Notification is a Request object without an "id" member.
  108. // The Server MUST NOT reply to a Notification, including those that are within a batch request.
  109. if request.ID == "" {
  110. logger.Debug("HTTPJSONRPC received a notification, skipping... (please send a non-empty ID if you want to call a method)")
  111. return
  112. }
  113. if len(r.URL.Path) > 1 {
  114. WriteRPCResponseHTTP(w, types.RPCInvalidRequestError(request.ID, errors.Errorf("Path %s is invalid", r.URL.Path)))
  115. return
  116. }
  117. rpcFunc := funcMap[request.Method]
  118. if rpcFunc == nil || rpcFunc.ws {
  119. WriteRPCResponseHTTP(w, types.RPCMethodNotFoundError(request.ID))
  120. return
  121. }
  122. var args []reflect.Value
  123. if len(request.Params) > 0 {
  124. args, err = jsonParamsToArgsRPC(rpcFunc, cdc, request.Params)
  125. if err != nil {
  126. WriteRPCResponseHTTP(w, types.RPCInvalidParamsError(request.ID, errors.Wrap(err, "Error converting json params to arguments")))
  127. return
  128. }
  129. }
  130. returns := rpcFunc.f.Call(args)
  131. logger.Info("HTTPJSONRPC", "method", request.Method, "args", args, "returns", returns)
  132. result, err := unreflectResult(returns)
  133. if err != nil {
  134. WriteRPCResponseHTTP(w, types.RPCInternalError(request.ID, err))
  135. return
  136. }
  137. WriteRPCResponseHTTP(w, types.NewRPCSuccessResponse(cdc, request.ID, result))
  138. }
  139. }
  140. func handleInvalidJSONRPCPaths(next http.HandlerFunc) http.HandlerFunc {
  141. return func(w http.ResponseWriter, r *http.Request) {
  142. // Since the pattern "/" matches all paths not matched by other registered patterns we check whether the path is indeed
  143. // "/", otherwise return a 404 error
  144. if r.URL.Path != "/" {
  145. http.NotFound(w, r)
  146. return
  147. }
  148. next(w, r)
  149. }
  150. }
  151. func mapParamsToArgs(rpcFunc *RPCFunc, cdc *amino.Codec, params map[string]json.RawMessage, argsOffset int) ([]reflect.Value, error) {
  152. values := make([]reflect.Value, len(rpcFunc.argNames))
  153. for i, argName := range rpcFunc.argNames {
  154. argType := rpcFunc.args[i+argsOffset]
  155. if p, ok := params[argName]; ok && p != nil && len(p) > 0 {
  156. val := reflect.New(argType)
  157. err := cdc.UnmarshalJSON(p, val.Interface())
  158. if err != nil {
  159. return nil, err
  160. }
  161. values[i] = val.Elem()
  162. } else { // use default for that type
  163. values[i] = reflect.Zero(argType)
  164. }
  165. }
  166. return values, nil
  167. }
  168. func arrayParamsToArgs(rpcFunc *RPCFunc, cdc *amino.Codec, params []json.RawMessage, argsOffset int) ([]reflect.Value, error) {
  169. if len(rpcFunc.argNames) != len(params) {
  170. return nil, errors.Errorf("Expected %v parameters (%v), got %v (%v)",
  171. len(rpcFunc.argNames), rpcFunc.argNames, len(params), params)
  172. }
  173. values := make([]reflect.Value, len(params))
  174. for i, p := range params {
  175. argType := rpcFunc.args[i+argsOffset]
  176. val := reflect.New(argType)
  177. err := cdc.UnmarshalJSON(p, val.Interface())
  178. if err != nil {
  179. return nil, err
  180. }
  181. values[i] = val.Elem()
  182. }
  183. return values, nil
  184. }
  185. // `raw` is unparsed json (from json.RawMessage) encoding either a map or an array.
  186. // `argsOffset` should be 0 for RPC calls, and 1 for WS requests, where len(rpcFunc.args) != len(rpcFunc.argNames).
  187. //
  188. // Example:
  189. // rpcFunc.args = [rpctypes.WSRPCContext string]
  190. // rpcFunc.argNames = ["arg"]
  191. func jsonParamsToArgs(rpcFunc *RPCFunc, cdc *amino.Codec, raw []byte, argsOffset int) ([]reflect.Value, error) {
  192. // TODO: Make more efficient, perhaps by checking the first character for '{' or '['?
  193. // First, try to get the map.
  194. var m map[string]json.RawMessage
  195. err := json.Unmarshal(raw, &m)
  196. if err == nil {
  197. return mapParamsToArgs(rpcFunc, cdc, m, argsOffset)
  198. }
  199. // Otherwise, try an array.
  200. var a []json.RawMessage
  201. err = json.Unmarshal(raw, &a)
  202. if err == nil {
  203. return arrayParamsToArgs(rpcFunc, cdc, a, argsOffset)
  204. }
  205. // Otherwise, bad format, we cannot parse
  206. return nil, errors.Errorf("Unknown type for JSON params: %v. Expected map or array", err)
  207. }
  208. // Convert a []interface{} OR a map[string]interface{} to properly typed values
  209. func jsonParamsToArgsRPC(rpcFunc *RPCFunc, cdc *amino.Codec, params json.RawMessage) ([]reflect.Value, error) {
  210. return jsonParamsToArgs(rpcFunc, cdc, params, 0)
  211. }
  212. // Same as above, but with the first param the websocket connection
  213. func jsonParamsToArgsWS(rpcFunc *RPCFunc, cdc *amino.Codec, params json.RawMessage, wsCtx types.WSRPCContext) ([]reflect.Value, error) {
  214. values, err := jsonParamsToArgs(rpcFunc, cdc, params, 1)
  215. if err != nil {
  216. return nil, err
  217. }
  218. return append([]reflect.Value{reflect.ValueOf(wsCtx)}, values...), nil
  219. }
  220. // rpc.json
  221. //-----------------------------------------------------------------------------
  222. // rpc.http
  223. // convert from a function name to the http handler
  224. func makeHTTPHandler(rpcFunc *RPCFunc, cdc *amino.Codec, logger log.Logger) func(http.ResponseWriter, *http.Request) {
  225. // Exception for websocket endpoints
  226. if rpcFunc.ws {
  227. return func(w http.ResponseWriter, r *http.Request) {
  228. WriteRPCResponseHTTP(w, types.RPCMethodNotFoundError(""))
  229. }
  230. }
  231. // All other endpoints
  232. return func(w http.ResponseWriter, r *http.Request) {
  233. logger.Debug("HTTP HANDLER", "req", r)
  234. args, err := httpParamsToArgs(rpcFunc, cdc, r)
  235. if err != nil {
  236. WriteRPCResponseHTTP(w, types.RPCInvalidParamsError("", errors.Wrap(err, "Error converting http params to arguments")))
  237. return
  238. }
  239. returns := rpcFunc.f.Call(args)
  240. logger.Info("HTTPRestRPC", "method", r.URL.Path, "args", args, "returns", returns)
  241. result, err := unreflectResult(returns)
  242. if err != nil {
  243. WriteRPCResponseHTTP(w, types.RPCInternalError("", err))
  244. return
  245. }
  246. WriteRPCResponseHTTP(w, types.NewRPCSuccessResponse(cdc, "", result))
  247. }
  248. }
  249. // Covert an http query to a list of properly typed values.
  250. // To be properly decoded the arg must be a concrete type from tendermint (if its an interface).
  251. func httpParamsToArgs(rpcFunc *RPCFunc, cdc *amino.Codec, r *http.Request) ([]reflect.Value, error) {
  252. values := make([]reflect.Value, len(rpcFunc.args))
  253. for i, name := range rpcFunc.argNames {
  254. argType := rpcFunc.args[i]
  255. values[i] = reflect.Zero(argType) // set default for that type
  256. arg := GetParam(r, name)
  257. // log.Notice("param to arg", "argType", argType, "name", name, "arg", arg)
  258. if "" == arg {
  259. continue
  260. }
  261. v, err, ok := nonJSONStringToArg(cdc, argType, arg)
  262. if err != nil {
  263. return nil, err
  264. }
  265. if ok {
  266. values[i] = v
  267. continue
  268. }
  269. values[i], err = jsonStringToArg(cdc, argType, arg)
  270. if err != nil {
  271. return nil, err
  272. }
  273. }
  274. return values, nil
  275. }
  276. func jsonStringToArg(cdc *amino.Codec, rt reflect.Type, arg string) (reflect.Value, error) {
  277. rv := reflect.New(rt)
  278. err := cdc.UnmarshalJSON([]byte(arg), rv.Interface())
  279. if err != nil {
  280. return rv, err
  281. }
  282. rv = rv.Elem()
  283. return rv, nil
  284. }
  285. func nonJSONStringToArg(cdc *amino.Codec, rt reflect.Type, arg string) (reflect.Value, error, bool) {
  286. if rt.Kind() == reflect.Ptr {
  287. rv_, err, ok := nonJSONStringToArg(cdc, rt.Elem(), arg)
  288. if err != nil {
  289. return reflect.Value{}, err, false
  290. } else if ok {
  291. rv := reflect.New(rt.Elem())
  292. rv.Elem().Set(rv_)
  293. return rv, nil, true
  294. } else {
  295. return reflect.Value{}, nil, false
  296. }
  297. } else {
  298. return _nonJSONStringToArg(cdc, rt, arg)
  299. }
  300. }
  301. // NOTE: rt.Kind() isn't a pointer.
  302. func _nonJSONStringToArg(cdc *amino.Codec, rt reflect.Type, arg string) (reflect.Value, error, bool) {
  303. isIntString := RE_INT.Match([]byte(arg))
  304. isQuotedString := strings.HasPrefix(arg, `"`) && strings.HasSuffix(arg, `"`)
  305. isHexString := strings.HasPrefix(strings.ToLower(arg), "0x")
  306. var expectingString, expectingByteSlice, expectingInt bool
  307. switch rt.Kind() {
  308. case reflect.Int, reflect.Uint, reflect.Int8, reflect.Uint8, reflect.Int16, reflect.Uint16, reflect.Int32, reflect.Uint32, reflect.Int64, reflect.Uint64:
  309. expectingInt = true
  310. case reflect.String:
  311. expectingString = true
  312. case reflect.Slice:
  313. expectingByteSlice = rt.Elem().Kind() == reflect.Uint8
  314. }
  315. if isIntString && expectingInt {
  316. qarg := `"` + arg + `"`
  317. // jsonStringToArg
  318. rv, err := jsonStringToArg(cdc, rt, qarg)
  319. if err != nil {
  320. return rv, err, false
  321. } else {
  322. return rv, nil, true
  323. }
  324. }
  325. if isHexString {
  326. if !expectingString && !expectingByteSlice {
  327. err := errors.Errorf("Got a hex string arg, but expected '%s'",
  328. rt.Kind().String())
  329. return reflect.ValueOf(nil), err, false
  330. }
  331. var value []byte
  332. value, err := hex.DecodeString(arg[2:])
  333. if err != nil {
  334. return reflect.ValueOf(nil), err, false
  335. }
  336. if rt.Kind() == reflect.String {
  337. return reflect.ValueOf(string(value)), nil, true
  338. }
  339. return reflect.ValueOf([]byte(value)), nil, true
  340. }
  341. if isQuotedString && expectingByteSlice {
  342. v := reflect.New(reflect.TypeOf(""))
  343. err := cdc.UnmarshalJSON([]byte(arg), v.Interface())
  344. if err != nil {
  345. return reflect.ValueOf(nil), err, false
  346. }
  347. v = v.Elem()
  348. return reflect.ValueOf([]byte(v.String())), nil, true
  349. }
  350. return reflect.ValueOf(nil), nil, false
  351. }
  352. // rpc.http
  353. //-----------------------------------------------------------------------------
  354. // rpc.websocket
  355. const (
  356. defaultWSWriteChanCapacity = 1000
  357. defaultWSWriteWait = 10 * time.Second
  358. defaultWSReadWait = 30 * time.Second
  359. defaultWSPingPeriod = (defaultWSReadWait * 9) / 10
  360. )
  361. // A single websocket connection contains listener id, underlying ws
  362. // connection, and the event switch for subscribing to events.
  363. //
  364. // In case of an error, the connection is stopped.
  365. type wsConnection struct {
  366. cmn.BaseService
  367. remoteAddr string
  368. baseConn *websocket.Conn
  369. writeChan chan types.RPCResponse
  370. funcMap map[string]*RPCFunc
  371. cdc *amino.Codec
  372. // write channel capacity
  373. writeChanCapacity int
  374. // each write times out after this.
  375. writeWait time.Duration
  376. // Connection times out if we haven't received *anything* in this long, not even pings.
  377. readWait time.Duration
  378. // Send pings to server with this period. Must be less than readWait, but greater than zero.
  379. pingPeriod time.Duration
  380. // object that is used to subscribe / unsubscribe from events
  381. eventSub types.EventSubscriber
  382. }
  383. // NewWSConnection wraps websocket.Conn.
  384. //
  385. // See the commentary on the func(*wsConnection) functions for a detailed
  386. // description of how to configure ping period and pong wait time. NOTE: if the
  387. // write buffer is full, pongs may be dropped, which may cause clients to
  388. // disconnect. see https://github.com/gorilla/websocket/issues/97
  389. func NewWSConnection(
  390. baseConn *websocket.Conn,
  391. funcMap map[string]*RPCFunc,
  392. cdc *amino.Codec,
  393. options ...func(*wsConnection),
  394. ) *wsConnection {
  395. baseConn.SetReadLimit(maxBodyBytes)
  396. wsc := &wsConnection{
  397. remoteAddr: baseConn.RemoteAddr().String(),
  398. baseConn: baseConn,
  399. funcMap: funcMap,
  400. cdc: cdc,
  401. writeWait: defaultWSWriteWait,
  402. writeChanCapacity: defaultWSWriteChanCapacity,
  403. readWait: defaultWSReadWait,
  404. pingPeriod: defaultWSPingPeriod,
  405. }
  406. for _, option := range options {
  407. option(wsc)
  408. }
  409. wsc.BaseService = *cmn.NewBaseService(nil, "wsConnection", wsc)
  410. return wsc
  411. }
  412. // EventSubscriber sets object that is used to subscribe / unsubscribe from
  413. // events - not Goroutine-safe. If none given, default node's eventBus will be
  414. // used.
  415. func EventSubscriber(eventSub types.EventSubscriber) func(*wsConnection) {
  416. return func(wsc *wsConnection) {
  417. wsc.eventSub = eventSub
  418. }
  419. }
  420. // WriteWait sets the amount of time to wait before a websocket write times out.
  421. // It should only be used in the constructor - not Goroutine-safe.
  422. func WriteWait(writeWait time.Duration) func(*wsConnection) {
  423. return func(wsc *wsConnection) {
  424. wsc.writeWait = writeWait
  425. }
  426. }
  427. // WriteChanCapacity sets the capacity of the websocket write channel.
  428. // It should only be used in the constructor - not Goroutine-safe.
  429. func WriteChanCapacity(cap int) func(*wsConnection) {
  430. return func(wsc *wsConnection) {
  431. wsc.writeChanCapacity = cap
  432. }
  433. }
  434. // ReadWait sets the amount of time to wait before a websocket read times out.
  435. // It should only be used in the constructor - not Goroutine-safe.
  436. func ReadWait(readWait time.Duration) func(*wsConnection) {
  437. return func(wsc *wsConnection) {
  438. wsc.readWait = readWait
  439. }
  440. }
  441. // PingPeriod sets the duration for sending websocket pings.
  442. // It should only be used in the constructor - not Goroutine-safe.
  443. func PingPeriod(pingPeriod time.Duration) func(*wsConnection) {
  444. return func(wsc *wsConnection) {
  445. wsc.pingPeriod = pingPeriod
  446. }
  447. }
  448. // OnStart implements cmn.Service by starting the read and write routines. It
  449. // blocks until the connection closes.
  450. func (wsc *wsConnection) OnStart() error {
  451. wsc.writeChan = make(chan types.RPCResponse, wsc.writeChanCapacity)
  452. // Read subscriptions/unsubscriptions to events
  453. go wsc.readRoutine()
  454. // Write responses, BLOCKING.
  455. wsc.writeRoutine()
  456. return nil
  457. }
  458. // OnStop implements cmn.Service by unsubscribing remoteAddr from all subscriptions.
  459. func (wsc *wsConnection) OnStop() {
  460. // Both read and write loops close the websocket connection when they exit their loops.
  461. // The writeChan is never closed, to allow WriteRPCResponse() to fail.
  462. if wsc.eventSub != nil {
  463. wsc.eventSub.UnsubscribeAll(context.TODO(), wsc.remoteAddr)
  464. }
  465. }
  466. // GetRemoteAddr returns the remote address of the underlying connection.
  467. // It implements WSRPCConnection
  468. func (wsc *wsConnection) GetRemoteAddr() string {
  469. return wsc.remoteAddr
  470. }
  471. // GetEventSubscriber implements WSRPCConnection by returning event subscriber.
  472. func (wsc *wsConnection) GetEventSubscriber() types.EventSubscriber {
  473. return wsc.eventSub
  474. }
  475. // WriteRPCResponse pushes a response to the writeChan, and blocks until it is accepted.
  476. // It implements WSRPCConnection. It is Goroutine-safe.
  477. func (wsc *wsConnection) WriteRPCResponse(resp types.RPCResponse) {
  478. select {
  479. case <-wsc.Quit():
  480. return
  481. case wsc.writeChan <- resp:
  482. }
  483. }
  484. // TryWriteRPCResponse attempts to push a response to the writeChan, but does not block.
  485. // It implements WSRPCConnection. It is Goroutine-safe
  486. func (wsc *wsConnection) TryWriteRPCResponse(resp types.RPCResponse) bool {
  487. select {
  488. case <-wsc.Quit():
  489. return false
  490. case wsc.writeChan <- resp:
  491. return true
  492. default:
  493. return false
  494. }
  495. }
  496. // Codec returns an amino codec used to decode parameters and encode results.
  497. // It implements WSRPCConnection.
  498. func (wsc *wsConnection) Codec() *amino.Codec {
  499. return wsc.cdc
  500. }
  501. // Read from the socket and subscribe to or unsubscribe from events
  502. func (wsc *wsConnection) readRoutine() {
  503. defer func() {
  504. if r := recover(); r != nil {
  505. err, ok := r.(error)
  506. if !ok {
  507. err = fmt.Errorf("WSJSONRPC: %v", r)
  508. }
  509. wsc.Logger.Error("Panic in WSJSONRPC handler", "err", err, "stack", string(debug.Stack()))
  510. wsc.WriteRPCResponse(types.RPCInternalError("unknown", err))
  511. go wsc.readRoutine()
  512. } else {
  513. wsc.baseConn.Close() // nolint: errcheck
  514. }
  515. }()
  516. wsc.baseConn.SetPongHandler(func(m string) error {
  517. return wsc.baseConn.SetReadDeadline(time.Now().Add(wsc.readWait))
  518. })
  519. for {
  520. select {
  521. case <-wsc.Quit():
  522. return
  523. default:
  524. // reset deadline for every type of message (control or data)
  525. if err := wsc.baseConn.SetReadDeadline(time.Now().Add(wsc.readWait)); err != nil {
  526. wsc.Logger.Error("failed to set read deadline", "err", err)
  527. }
  528. var in []byte
  529. _, in, err := wsc.baseConn.ReadMessage()
  530. if err != nil {
  531. if websocket.IsCloseError(err, websocket.CloseNormalClosure) {
  532. wsc.Logger.Info("Client closed the connection")
  533. } else {
  534. wsc.Logger.Error("Failed to read request", "err", err)
  535. }
  536. wsc.Stop()
  537. return
  538. }
  539. var request types.RPCRequest
  540. err = json.Unmarshal(in, &request)
  541. if err != nil {
  542. wsc.WriteRPCResponse(types.RPCParseError("", errors.Wrap(err, "Error unmarshaling request")))
  543. continue
  544. }
  545. // A Notification is a Request object without an "id" member.
  546. // The Server MUST NOT reply to a Notification, including those that are within a batch request.
  547. if request.ID == "" {
  548. wsc.Logger.Debug("WSJSONRPC received a notification, skipping... (please send a non-empty ID if you want to call a method)")
  549. continue
  550. }
  551. // Now, fetch the RPCFunc and execute it.
  552. rpcFunc := wsc.funcMap[request.Method]
  553. if rpcFunc == nil {
  554. wsc.WriteRPCResponse(types.RPCMethodNotFoundError(request.ID))
  555. continue
  556. }
  557. var args []reflect.Value
  558. if rpcFunc.ws {
  559. wsCtx := types.WSRPCContext{Request: request, WSRPCConnection: wsc}
  560. if len(request.Params) > 0 {
  561. args, err = jsonParamsToArgsWS(rpcFunc, wsc.cdc, request.Params, wsCtx)
  562. }
  563. } else {
  564. if len(request.Params) > 0 {
  565. args, err = jsonParamsToArgsRPC(rpcFunc, wsc.cdc, request.Params)
  566. }
  567. }
  568. if err != nil {
  569. wsc.WriteRPCResponse(types.RPCInternalError(request.ID, errors.Wrap(err, "Error converting json params to arguments")))
  570. continue
  571. }
  572. returns := rpcFunc.f.Call(args)
  573. // TODO: Need to encode args/returns to string if we want to log them
  574. wsc.Logger.Info("WSJSONRPC", "method", request.Method)
  575. result, err := unreflectResult(returns)
  576. if err != nil {
  577. wsc.WriteRPCResponse(types.RPCInternalError(request.ID, err))
  578. continue
  579. }
  580. wsc.WriteRPCResponse(types.NewRPCSuccessResponse(wsc.cdc, request.ID, result))
  581. }
  582. }
  583. }
  584. // receives on a write channel and writes out on the socket
  585. func (wsc *wsConnection) writeRoutine() {
  586. pingTicker := time.NewTicker(wsc.pingPeriod)
  587. defer func() {
  588. pingTicker.Stop()
  589. if err := wsc.baseConn.Close(); err != nil {
  590. wsc.Logger.Error("Error closing connection", "err", err)
  591. }
  592. }()
  593. // https://github.com/gorilla/websocket/issues/97
  594. pongs := make(chan string, 1)
  595. wsc.baseConn.SetPingHandler(func(m string) error {
  596. select {
  597. case pongs <- m:
  598. default:
  599. }
  600. return nil
  601. })
  602. for {
  603. select {
  604. case m := <-pongs:
  605. err := wsc.writeMessageWithDeadline(websocket.PongMessage, []byte(m))
  606. if err != nil {
  607. wsc.Logger.Info("Failed to write pong (client may disconnect)", "err", err)
  608. }
  609. case <-pingTicker.C:
  610. err := wsc.writeMessageWithDeadline(websocket.PingMessage, []byte{})
  611. if err != nil {
  612. wsc.Logger.Error("Failed to write ping", "err", err)
  613. wsc.Stop()
  614. return
  615. }
  616. case msg := <-wsc.writeChan:
  617. jsonBytes, err := json.MarshalIndent(msg, "", " ")
  618. if err != nil {
  619. wsc.Logger.Error("Failed to marshal RPCResponse to JSON", "err", err)
  620. } else {
  621. if err = wsc.writeMessageWithDeadline(websocket.TextMessage, jsonBytes); err != nil {
  622. wsc.Logger.Error("Failed to write response", "err", err)
  623. wsc.Stop()
  624. return
  625. }
  626. }
  627. case <-wsc.Quit():
  628. return
  629. }
  630. }
  631. }
  632. // All writes to the websocket must (re)set the write deadline.
  633. // If some writes don't set it while others do, they may timeout incorrectly (https://github.com/tendermint/tendermint/issues/553)
  634. func (wsc *wsConnection) writeMessageWithDeadline(msgType int, msg []byte) error {
  635. if err := wsc.baseConn.SetWriteDeadline(time.Now().Add(wsc.writeWait)); err != nil {
  636. return err
  637. }
  638. return wsc.baseConn.WriteMessage(msgType, msg)
  639. }
  640. //----------------------------------------
  641. // WebsocketManager provides a WS handler for incoming connections and passes a
  642. // map of functions along with any additional params to new connections.
  643. // NOTE: The websocket path is defined externally, e.g. in node/node.go
  644. type WebsocketManager struct {
  645. websocket.Upgrader
  646. funcMap map[string]*RPCFunc
  647. cdc *amino.Codec
  648. logger log.Logger
  649. wsConnOptions []func(*wsConnection)
  650. }
  651. // NewWebsocketManager returns a new WebsocketManager that passes a map of
  652. // functions, connection options and logger to new WS connections.
  653. func NewWebsocketManager(funcMap map[string]*RPCFunc, cdc *amino.Codec, wsConnOptions ...func(*wsConnection)) *WebsocketManager {
  654. return &WebsocketManager{
  655. funcMap: funcMap,
  656. cdc: cdc,
  657. Upgrader: websocket.Upgrader{
  658. CheckOrigin: func(r *http.Request) bool {
  659. // TODO ???
  660. return true
  661. },
  662. },
  663. logger: log.NewNopLogger(),
  664. wsConnOptions: wsConnOptions,
  665. }
  666. }
  667. // SetLogger sets the logger.
  668. func (wm *WebsocketManager) SetLogger(l log.Logger) {
  669. wm.logger = l
  670. }
  671. // WebsocketHandler upgrades the request/response (via http.Hijack) and starts
  672. // the wsConnection.
  673. func (wm *WebsocketManager) WebsocketHandler(w http.ResponseWriter, r *http.Request) {
  674. wsConn, err := wm.Upgrade(w, r, nil)
  675. if err != nil {
  676. // TODO - return http error
  677. wm.logger.Error("Failed to upgrade to websocket connection", "err", err)
  678. return
  679. }
  680. // register connection
  681. con := NewWSConnection(wsConn, wm.funcMap, wm.cdc, wm.wsConnOptions...)
  682. con.SetLogger(wm.logger.With("remote", wsConn.RemoteAddr()))
  683. wm.logger.Info("New websocket connection", "remote", con.remoteAddr)
  684. err = con.Start() // Blocking
  685. if err != nil {
  686. wm.logger.Error("Error starting connection", "err", err)
  687. }
  688. }
  689. // rpc.websocket
  690. //-----------------------------------------------------------------------------
  691. // NOTE: assume returns is result struct and error. If error is not nil, return it
  692. func unreflectResult(returns []reflect.Value) (interface{}, error) {
  693. errV := returns[1]
  694. if errV.Interface() != nil {
  695. return nil, errors.Errorf("%v", errV.Interface())
  696. }
  697. rv := returns[0]
  698. // the result is a registered interface,
  699. // we need a pointer to it so we can marshal with type byte
  700. rvp := reflect.New(rv.Type())
  701. rvp.Elem().Set(rv)
  702. return rvp.Interface(), nil
  703. }
  704. // writes a list of available rpc endpoints as an html page
  705. func writeListOfEndpoints(w http.ResponseWriter, r *http.Request, funcMap map[string]*RPCFunc) {
  706. noArgNames := []string{}
  707. argNames := []string{}
  708. for name, funcData := range funcMap {
  709. if len(funcData.args) == 0 {
  710. noArgNames = append(noArgNames, name)
  711. } else {
  712. argNames = append(argNames, name)
  713. }
  714. }
  715. sort.Strings(noArgNames)
  716. sort.Strings(argNames)
  717. buf := new(bytes.Buffer)
  718. buf.WriteString("<html><body>")
  719. buf.WriteString("<br>Available endpoints:<br>")
  720. for _, name := range noArgNames {
  721. link := fmt.Sprintf("//%s/%s", r.Host, name)
  722. buf.WriteString(fmt.Sprintf("<a href=\"%s\">%s</a></br>", link, link))
  723. }
  724. buf.WriteString("<br>Endpoints that require arguments:<br>")
  725. for _, name := range argNames {
  726. link := fmt.Sprintf("//%s/%s?", r.Host, name)
  727. funcData := funcMap[name]
  728. for i, argName := range funcData.argNames {
  729. link += argName + "=_"
  730. if i < len(funcData.argNames)-1 {
  731. link += "&"
  732. }
  733. }
  734. buf.WriteString(fmt.Sprintf("<a href=\"%s\">%s</a></br>", link, link))
  735. }
  736. buf.WriteString("</body></html>")
  737. w.Header().Set("Content-Type", "text/html")
  738. w.WriteHeader(200)
  739. w.Write(buf.Bytes()) // nolint: errcheck
  740. }