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.

794 lines
24 KiB

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
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
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
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. types "github.com/tendermint/tendermint/rpc/lib/types"
  19. cmn "github.com/tendermint/tmlibs/common"
  20. "github.com/tendermint/tmlibs/log"
  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 := nonJSONToArg(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, ty reflect.Type, arg string) (reflect.Value, error) {
  277. v := reflect.New(ty)
  278. err := cdc.UnmarshalJSON([]byte(arg), v.Interface())
  279. if err != nil {
  280. return v, err
  281. }
  282. v = v.Elem()
  283. return v, nil
  284. }
  285. func nonJSONToArg(cdc *amino.Codec, ty reflect.Type, arg string) (reflect.Value, error, bool) {
  286. isQuotedString := strings.HasPrefix(arg, `"`) && strings.HasSuffix(arg, `"`)
  287. isHexString := strings.HasPrefix(strings.ToLower(arg), "0x")
  288. expectingString := ty.Kind() == reflect.String
  289. expectingByteSlice := ty.Kind() == reflect.Slice && ty.Elem().Kind() == reflect.Uint8
  290. if isHexString {
  291. if !expectingString && !expectingByteSlice {
  292. err := errors.Errorf("Got a hex string arg, but expected '%s'",
  293. ty.Kind().String())
  294. return reflect.ValueOf(nil), err, false
  295. }
  296. var value []byte
  297. value, err := hex.DecodeString(arg[2:])
  298. if err != nil {
  299. return reflect.ValueOf(nil), err, false
  300. }
  301. if ty.Kind() == reflect.String {
  302. return reflect.ValueOf(string(value)), nil, true
  303. }
  304. return reflect.ValueOf([]byte(value)), nil, true
  305. }
  306. if isQuotedString && expectingByteSlice {
  307. v := reflect.New(reflect.TypeOf(""))
  308. err := cdc.UnmarshalJSON([]byte(arg), v.Interface())
  309. if err != nil {
  310. return reflect.ValueOf(nil), err, false
  311. }
  312. v = v.Elem()
  313. return reflect.ValueOf([]byte(v.String())), nil, true
  314. }
  315. return reflect.ValueOf(nil), nil, false
  316. }
  317. // rpc.http
  318. //-----------------------------------------------------------------------------
  319. // rpc.websocket
  320. const (
  321. defaultWSWriteChanCapacity = 1000
  322. defaultWSWriteWait = 10 * time.Second
  323. defaultWSReadWait = 30 * time.Second
  324. defaultWSPingPeriod = (defaultWSReadWait * 9) / 10
  325. )
  326. // A single websocket connection contains listener id, underlying ws
  327. // connection, and the event switch for subscribing to events.
  328. //
  329. // In case of an error, the connection is stopped.
  330. type wsConnection struct {
  331. cmn.BaseService
  332. remoteAddr string
  333. baseConn *websocket.Conn
  334. writeChan chan types.RPCResponse
  335. funcMap map[string]*RPCFunc
  336. cdc *amino.Codec
  337. // write channel capacity
  338. writeChanCapacity int
  339. // each write times out after this.
  340. writeWait time.Duration
  341. // Connection times out if we haven't received *anything* in this long, not even pings.
  342. readWait time.Duration
  343. // Send pings to server with this period. Must be less than readWait, but greater than zero.
  344. pingPeriod time.Duration
  345. // object that is used to subscribe / unsubscribe from events
  346. eventSub types.EventSubscriber
  347. }
  348. // NewWSConnection wraps websocket.Conn.
  349. //
  350. // See the commentary on the func(*wsConnection) functions for a detailed
  351. // description of how to configure ping period and pong wait time. NOTE: if the
  352. // write buffer is full, pongs may be dropped, which may cause clients to
  353. // disconnect. see https://github.com/gorilla/websocket/issues/97
  354. func NewWSConnection(baseConn *websocket.Conn, funcMap map[string]*RPCFunc, cdc *amino.Codec, options ...func(*wsConnection)) *wsConnection {
  355. wsc := &wsConnection{
  356. remoteAddr: baseConn.RemoteAddr().String(),
  357. baseConn: baseConn,
  358. funcMap: funcMap,
  359. cdc: cdc,
  360. writeWait: defaultWSWriteWait,
  361. writeChanCapacity: defaultWSWriteChanCapacity,
  362. readWait: defaultWSReadWait,
  363. pingPeriod: defaultWSPingPeriod,
  364. }
  365. for _, option := range options {
  366. option(wsc)
  367. }
  368. wsc.BaseService = *cmn.NewBaseService(nil, "wsConnection", wsc)
  369. return wsc
  370. }
  371. // EventSubscriber sets object that is used to subscribe / unsubscribe from
  372. // events - not Goroutine-safe. If none given, default node's eventBus will be
  373. // used.
  374. func EventSubscriber(eventSub types.EventSubscriber) func(*wsConnection) {
  375. return func(wsc *wsConnection) {
  376. wsc.eventSub = eventSub
  377. }
  378. }
  379. // WriteWait sets the amount of time to wait before a websocket write times out.
  380. // It should only be used in the constructor - not Goroutine-safe.
  381. func WriteWait(writeWait time.Duration) func(*wsConnection) {
  382. return func(wsc *wsConnection) {
  383. wsc.writeWait = writeWait
  384. }
  385. }
  386. // WriteChanCapacity sets the capacity of the websocket write channel.
  387. // It should only be used in the constructor - not Goroutine-safe.
  388. func WriteChanCapacity(cap int) func(*wsConnection) {
  389. return func(wsc *wsConnection) {
  390. wsc.writeChanCapacity = cap
  391. }
  392. }
  393. // ReadWait sets the amount of time to wait before a websocket read times out.
  394. // It should only be used in the constructor - not Goroutine-safe.
  395. func ReadWait(readWait time.Duration) func(*wsConnection) {
  396. return func(wsc *wsConnection) {
  397. wsc.readWait = readWait
  398. }
  399. }
  400. // PingPeriod sets the duration for sending websocket pings.
  401. // It should only be used in the constructor - not Goroutine-safe.
  402. func PingPeriod(pingPeriod time.Duration) func(*wsConnection) {
  403. return func(wsc *wsConnection) {
  404. wsc.pingPeriod = pingPeriod
  405. }
  406. }
  407. // OnStart implements cmn.Service by starting the read and write routines. It
  408. // blocks until the connection closes.
  409. func (wsc *wsConnection) OnStart() error {
  410. wsc.writeChan = make(chan types.RPCResponse, wsc.writeChanCapacity)
  411. // Read subscriptions/unsubscriptions to events
  412. go wsc.readRoutine()
  413. // Write responses, BLOCKING.
  414. wsc.writeRoutine()
  415. return nil
  416. }
  417. // OnStop implements cmn.Service by unsubscribing remoteAddr from all subscriptions.
  418. func (wsc *wsConnection) OnStop() {
  419. // Both read and write loops close the websocket connection when they exit their loops.
  420. // The writeChan is never closed, to allow WriteRPCResponse() to fail.
  421. if wsc.eventSub != nil {
  422. wsc.eventSub.UnsubscribeAll(context.TODO(), wsc.remoteAddr)
  423. }
  424. }
  425. // GetRemoteAddr returns the remote address of the underlying connection.
  426. // It implements WSRPCConnection
  427. func (wsc *wsConnection) GetRemoteAddr() string {
  428. return wsc.remoteAddr
  429. }
  430. // GetEventSubscriber implements WSRPCConnection by returning event subscriber.
  431. func (wsc *wsConnection) GetEventSubscriber() types.EventSubscriber {
  432. return wsc.eventSub
  433. }
  434. // WriteRPCResponse pushes a response to the writeChan, and blocks until it is accepted.
  435. // It implements WSRPCConnection. It is Goroutine-safe.
  436. func (wsc *wsConnection) WriteRPCResponse(resp types.RPCResponse) {
  437. select {
  438. case <-wsc.Quit():
  439. return
  440. case wsc.writeChan <- resp:
  441. }
  442. }
  443. // TryWriteRPCResponse attempts to push a response to the writeChan, but does not block.
  444. // It implements WSRPCConnection. It is Goroutine-safe
  445. func (wsc *wsConnection) TryWriteRPCResponse(resp types.RPCResponse) bool {
  446. select {
  447. case <-wsc.Quit():
  448. return false
  449. case wsc.writeChan <- resp:
  450. return true
  451. default:
  452. return false
  453. }
  454. }
  455. // Codec returns an amino codec used to decode parameters and encode results.
  456. // It implements WSRPCConnection.
  457. func (wsc *wsConnection) Codec() *amino.Codec {
  458. return wsc.cdc
  459. }
  460. // Read from the socket and subscribe to or unsubscribe from events
  461. func (wsc *wsConnection) readRoutine() {
  462. defer func() {
  463. if r := recover(); r != nil {
  464. err, ok := r.(error)
  465. if !ok {
  466. err = fmt.Errorf("WSJSONRPC: %v", r)
  467. }
  468. wsc.Logger.Error("Panic in WSJSONRPC handler", "err", err, "stack", string(debug.Stack()))
  469. wsc.WriteRPCResponse(types.RPCInternalError("unknown", err))
  470. go wsc.readRoutine()
  471. } else {
  472. wsc.baseConn.Close() // nolint: errcheck
  473. }
  474. }()
  475. wsc.baseConn.SetPongHandler(func(m string) error {
  476. return wsc.baseConn.SetReadDeadline(time.Now().Add(wsc.readWait))
  477. })
  478. for {
  479. select {
  480. case <-wsc.Quit():
  481. return
  482. default:
  483. // reset deadline for every type of message (control or data)
  484. if err := wsc.baseConn.SetReadDeadline(time.Now().Add(wsc.readWait)); err != nil {
  485. wsc.Logger.Error("failed to set read deadline", "err", err)
  486. }
  487. var in []byte
  488. _, in, err := wsc.baseConn.ReadMessage()
  489. if err != nil {
  490. if websocket.IsCloseError(err, websocket.CloseNormalClosure) {
  491. wsc.Logger.Info("Client closed the connection")
  492. } else {
  493. wsc.Logger.Error("Failed to read request", "err", err)
  494. }
  495. wsc.Stop()
  496. return
  497. }
  498. var request types.RPCRequest
  499. err = json.Unmarshal(in, &request)
  500. if err != nil {
  501. wsc.WriteRPCResponse(types.RPCParseError("", errors.Wrap(err, "Error unmarshaling request")))
  502. continue
  503. }
  504. // A Notification is a Request object without an "id" member.
  505. // The Server MUST NOT reply to a Notification, including those that are within a batch request.
  506. if request.ID == "" {
  507. wsc.Logger.Debug("WSJSONRPC received a notification, skipping... (please send a non-empty ID if you want to call a method)")
  508. continue
  509. }
  510. // Now, fetch the RPCFunc and execute it.
  511. rpcFunc := wsc.funcMap[request.Method]
  512. if rpcFunc == nil {
  513. wsc.WriteRPCResponse(types.RPCMethodNotFoundError(request.ID))
  514. continue
  515. }
  516. var args []reflect.Value
  517. if rpcFunc.ws {
  518. wsCtx := types.WSRPCContext{Request: request, WSRPCConnection: wsc}
  519. if len(request.Params) > 0 {
  520. args, err = jsonParamsToArgsWS(rpcFunc, wsc.cdc, request.Params, wsCtx)
  521. }
  522. } else {
  523. if len(request.Params) > 0 {
  524. args, err = jsonParamsToArgsRPC(rpcFunc, wsc.cdc, request.Params)
  525. }
  526. }
  527. if err != nil {
  528. wsc.WriteRPCResponse(types.RPCInternalError(request.ID, errors.Wrap(err, "Error converting json params to arguments")))
  529. continue
  530. }
  531. returns := rpcFunc.f.Call(args)
  532. // TODO: Need to encode args/returns to string if we want to log them
  533. wsc.Logger.Info("WSJSONRPC", "method", request.Method)
  534. result, err := unreflectResult(returns)
  535. if err != nil {
  536. wsc.WriteRPCResponse(types.RPCInternalError(request.ID, err))
  537. continue
  538. }
  539. wsc.WriteRPCResponse(types.NewRPCSuccessResponse(wsc.cdc, request.ID, result))
  540. }
  541. }
  542. }
  543. // receives on a write channel and writes out on the socket
  544. func (wsc *wsConnection) writeRoutine() {
  545. pingTicker := time.NewTicker(wsc.pingPeriod)
  546. defer func() {
  547. pingTicker.Stop()
  548. if err := wsc.baseConn.Close(); err != nil {
  549. wsc.Logger.Error("Error closing connection", "err", err)
  550. }
  551. }()
  552. // https://github.com/gorilla/websocket/issues/97
  553. pongs := make(chan string, 1)
  554. wsc.baseConn.SetPingHandler(func(m string) error {
  555. select {
  556. case pongs <- m:
  557. default:
  558. }
  559. return nil
  560. })
  561. for {
  562. select {
  563. case m := <-pongs:
  564. err := wsc.writeMessageWithDeadline(websocket.PongMessage, []byte(m))
  565. if err != nil {
  566. wsc.Logger.Info("Failed to write pong (client may disconnect)", "err", err)
  567. }
  568. case <-pingTicker.C:
  569. err := wsc.writeMessageWithDeadline(websocket.PingMessage, []byte{})
  570. if err != nil {
  571. wsc.Logger.Error("Failed to write ping", "err", err)
  572. wsc.Stop()
  573. return
  574. }
  575. case msg := <-wsc.writeChan:
  576. jsonBytes, err := json.MarshalIndent(msg, "", " ")
  577. if err != nil {
  578. wsc.Logger.Error("Failed to marshal RPCResponse to JSON", "err", err)
  579. } else {
  580. if err = wsc.writeMessageWithDeadline(websocket.TextMessage, jsonBytes); err != nil {
  581. wsc.Logger.Error("Failed to write response", "err", err)
  582. wsc.Stop()
  583. return
  584. }
  585. }
  586. case <-wsc.Quit():
  587. return
  588. }
  589. }
  590. }
  591. // All writes to the websocket must (re)set the write deadline.
  592. // If some writes don't set it while others do, they may timeout incorrectly (https://github.com/tendermint/tendermint/issues/553)
  593. func (wsc *wsConnection) writeMessageWithDeadline(msgType int, msg []byte) error {
  594. if err := wsc.baseConn.SetWriteDeadline(time.Now().Add(wsc.writeWait)); err != nil {
  595. return err
  596. }
  597. return wsc.baseConn.WriteMessage(msgType, msg)
  598. }
  599. //----------------------------------------
  600. // WebsocketManager provides a WS handler for incoming connections and passes a
  601. // map of functions along with any additional params to new connections.
  602. // NOTE: The websocket path is defined externally, e.g. in node/node.go
  603. type WebsocketManager struct {
  604. websocket.Upgrader
  605. funcMap map[string]*RPCFunc
  606. cdc *amino.Codec
  607. logger log.Logger
  608. wsConnOptions []func(*wsConnection)
  609. }
  610. // NewWebsocketManager returns a new WebsocketManager that passes a map of
  611. // functions, connection options and logger to new WS connections.
  612. func NewWebsocketManager(funcMap map[string]*RPCFunc, cdc *amino.Codec, wsConnOptions ...func(*wsConnection)) *WebsocketManager {
  613. return &WebsocketManager{
  614. funcMap: funcMap,
  615. cdc: cdc,
  616. Upgrader: websocket.Upgrader{
  617. CheckOrigin: func(r *http.Request) bool {
  618. // TODO ???
  619. return true
  620. },
  621. },
  622. logger: log.NewNopLogger(),
  623. wsConnOptions: wsConnOptions,
  624. }
  625. }
  626. // SetLogger sets the logger.
  627. func (wm *WebsocketManager) SetLogger(l log.Logger) {
  628. wm.logger = l
  629. }
  630. // WebsocketHandler upgrades the request/response (via http.Hijack) and starts
  631. // the wsConnection.
  632. func (wm *WebsocketManager) WebsocketHandler(w http.ResponseWriter, r *http.Request) {
  633. wsConn, err := wm.Upgrade(w, r, nil)
  634. if err != nil {
  635. // TODO - return http error
  636. wm.logger.Error("Failed to upgrade to websocket connection", "err", err)
  637. return
  638. }
  639. // register connection
  640. con := NewWSConnection(wsConn, wm.funcMap, wm.cdc, wm.wsConnOptions...)
  641. con.SetLogger(wm.logger.With("remote", wsConn.RemoteAddr()))
  642. wm.logger.Info("New websocket connection", "remote", con.remoteAddr)
  643. err = con.Start() // Blocking
  644. if err != nil {
  645. wm.logger.Error("Error starting connection", "err", err)
  646. }
  647. }
  648. // rpc.websocket
  649. //-----------------------------------------------------------------------------
  650. // NOTE: assume returns is result struct and error. If error is not nil, return it
  651. func unreflectResult(returns []reflect.Value) (interface{}, error) {
  652. errV := returns[1]
  653. if errV.Interface() != nil {
  654. return nil, errors.Errorf("%v", errV.Interface())
  655. }
  656. rv := returns[0]
  657. // the result is a registered interface,
  658. // we need a pointer to it so we can marshal with type byte
  659. rvp := reflect.New(rv.Type())
  660. rvp.Elem().Set(rv)
  661. return rvp.Interface(), nil
  662. }
  663. // writes a list of available rpc endpoints as an html page
  664. func writeListOfEndpoints(w http.ResponseWriter, r *http.Request, funcMap map[string]*RPCFunc) {
  665. noArgNames := []string{}
  666. argNames := []string{}
  667. for name, funcData := range funcMap {
  668. if len(funcData.args) == 0 {
  669. noArgNames = append(noArgNames, name)
  670. } else {
  671. argNames = append(argNames, name)
  672. }
  673. }
  674. sort.Strings(noArgNames)
  675. sort.Strings(argNames)
  676. buf := new(bytes.Buffer)
  677. buf.WriteString("<html><body>")
  678. buf.WriteString("<br>Available endpoints:<br>")
  679. for _, name := range noArgNames {
  680. link := fmt.Sprintf("//%s/%s", r.Host, name)
  681. buf.WriteString(fmt.Sprintf("<a href=\"%s\">%s</a></br>", link, link))
  682. }
  683. buf.WriteString("<br>Endpoints that require arguments:<br>")
  684. for _, name := range argNames {
  685. link := fmt.Sprintf("//%s/%s?", r.Host, name)
  686. funcData := funcMap[name]
  687. for i, argName := range funcData.argNames {
  688. link += argName + "=_"
  689. if i < len(funcData.argNames)-1 {
  690. link += "&"
  691. }
  692. }
  693. buf.WriteString(fmt.Sprintf("<a href=\"%s\">%s</a></br>", link, link))
  694. }
  695. buf.WriteString("</body></html>")
  696. w.Header().Set("Content-Type", "text/html")
  697. w.WriteHeader(200)
  698. w.Write(buf.Bytes()) // nolint: errcheck
  699. }