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.

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