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.

447 lines
11 KiB

8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
9 years ago
8 years ago
9 years ago
8 years ago
9 years ago
9 years ago
8 years ago
8 years ago
8 years ago
8 years ago
  1. package abcicli
  2. import (
  3. "bufio"
  4. "container/list"
  5. "errors"
  6. "fmt"
  7. "net"
  8. "reflect"
  9. "sync"
  10. "time"
  11. "github.com/tendermint/abci/types"
  12. cmn "github.com/tendermint/tmlibs/common"
  13. )
  14. const (
  15. OK = types.CodeType_OK
  16. LOG = ""
  17. )
  18. const reqQueueSize = 256 // TODO make configurable
  19. const maxResponseSize = 1048576 // 1MB TODO make configurable
  20. const flushThrottleMS = 20 // Don't wait longer than...
  21. // This is goroutine-safe, but users should beware that
  22. // the application in general is not meant to be interfaced
  23. // with concurrent callers.
  24. type socketClient struct {
  25. cmn.BaseService
  26. reqQueue chan *ReqRes
  27. flushTimer *cmn.ThrottleTimer
  28. mustConnect bool
  29. mtx sync.Mutex
  30. addr string
  31. conn net.Conn
  32. err error
  33. reqSent *list.List
  34. resCb func(*types.Request, *types.Response) // listens to all callbacks
  35. }
  36. func NewSocketClient(addr string, mustConnect bool) (*socketClient, error) {
  37. cli := &socketClient{
  38. reqQueue: make(chan *ReqRes, reqQueueSize),
  39. flushTimer: cmn.NewThrottleTimer("socketClient", flushThrottleMS),
  40. mustConnect: mustConnect,
  41. addr: addr,
  42. reqSent: list.New(),
  43. resCb: nil,
  44. }
  45. cli.BaseService = *cmn.NewBaseService(nil, "socketClient", cli)
  46. // FIXME we are loosing "Starting socketClient" message here
  47. // add logger to params?
  48. _, err := cli.Start() // Just start it, it's confusing for callers to remember to start.
  49. return cli, err
  50. }
  51. func (cli *socketClient) OnStart() error {
  52. cli.BaseService.OnStart()
  53. var err error
  54. var conn net.Conn
  55. RETRY_LOOP:
  56. for {
  57. conn, err = cmn.Connect(cli.addr)
  58. if err != nil {
  59. if cli.mustConnect {
  60. return err
  61. }
  62. cli.Logger.Error(fmt.Sprintf("abci.socketClient failed to connect to %v. Retrying...", cli.addr))
  63. time.Sleep(time.Second * 3)
  64. continue RETRY_LOOP
  65. }
  66. cli.conn = conn
  67. go cli.sendRequestsRoutine(conn)
  68. go cli.recvResponseRoutine(conn)
  69. return nil
  70. }
  71. }
  72. func (cli *socketClient) OnStop() {
  73. cli.BaseService.OnStop()
  74. cli.mtx.Lock()
  75. defer cli.mtx.Unlock()
  76. if cli.conn != nil {
  77. cli.conn.Close()
  78. }
  79. cli.flushQueue()
  80. }
  81. // Stop the client and set the error
  82. func (cli *socketClient) StopForError(err error) {
  83. cli.mtx.Lock()
  84. if !cli.IsRunning() {
  85. return
  86. }
  87. if cli.err == nil {
  88. cli.err = err
  89. }
  90. cli.mtx.Unlock()
  91. cli.Logger.Error(fmt.Sprintf("Stopping abci.socketClient for error: %v", err.Error()))
  92. cli.Stop()
  93. }
  94. func (cli *socketClient) Error() error {
  95. cli.mtx.Lock()
  96. defer cli.mtx.Unlock()
  97. return cli.err
  98. }
  99. // Set listener for all responses
  100. // NOTE: callback may get internally generated flush responses.
  101. func (cli *socketClient) SetResponseCallback(resCb Callback) {
  102. cli.mtx.Lock()
  103. defer cli.mtx.Unlock()
  104. cli.resCb = resCb
  105. }
  106. //----------------------------------------
  107. func (cli *socketClient) sendRequestsRoutine(conn net.Conn) {
  108. w := bufio.NewWriter(conn)
  109. for {
  110. select {
  111. case <-cli.flushTimer.Ch:
  112. select {
  113. case cli.reqQueue <- NewReqRes(types.ToRequestFlush()):
  114. default:
  115. // Probably will fill the buffer, or retry later.
  116. }
  117. case <-cli.BaseService.Quit:
  118. return
  119. case reqres := <-cli.reqQueue:
  120. cli.willSendReq(reqres)
  121. err := types.WriteMessage(reqres.Request, w)
  122. if err != nil {
  123. cli.StopForError(fmt.Errorf("Error writing msg: %v", err))
  124. return
  125. }
  126. // cli.Logger.Debug("Sent request", "requestType", reflect.TypeOf(reqres.Request), "request", reqres.Request)
  127. if _, ok := reqres.Request.Value.(*types.Request_Flush); ok {
  128. err = w.Flush()
  129. if err != nil {
  130. cli.StopForError(fmt.Errorf("Error flushing writer: %v", err))
  131. return
  132. }
  133. }
  134. }
  135. }
  136. }
  137. func (cli *socketClient) recvResponseRoutine(conn net.Conn) {
  138. r := bufio.NewReader(conn) // Buffer reads
  139. for {
  140. var res = &types.Response{}
  141. err := types.ReadMessage(r, res)
  142. if err != nil {
  143. cli.StopForError(err)
  144. return
  145. }
  146. switch r := res.Value.(type) {
  147. case *types.Response_Exception:
  148. // XXX After setting cli.err, release waiters (e.g. reqres.Done())
  149. cli.StopForError(errors.New(r.Exception.Error))
  150. return
  151. default:
  152. // cli.Logger.Debug("Received response", "responseType", reflect.TypeOf(res), "response", res)
  153. err := cli.didRecvResponse(res)
  154. if err != nil {
  155. cli.StopForError(err)
  156. return
  157. }
  158. }
  159. }
  160. }
  161. func (cli *socketClient) willSendReq(reqres *ReqRes) {
  162. cli.mtx.Lock()
  163. defer cli.mtx.Unlock()
  164. cli.reqSent.PushBack(reqres)
  165. }
  166. func (cli *socketClient) didRecvResponse(res *types.Response) error {
  167. cli.mtx.Lock()
  168. defer cli.mtx.Unlock()
  169. // Get the first ReqRes
  170. next := cli.reqSent.Front()
  171. if next == nil {
  172. return fmt.Errorf("Unexpected result type %v when nothing expected", reflect.TypeOf(res.Value))
  173. }
  174. reqres := next.Value.(*ReqRes)
  175. if !resMatchesReq(reqres.Request, res) {
  176. return fmt.Errorf("Unexpected result type %v when response to %v expected",
  177. reflect.TypeOf(res.Value), reflect.TypeOf(reqres.Request.Value))
  178. }
  179. reqres.Response = res // Set response
  180. reqres.Done() // Release waiters
  181. cli.reqSent.Remove(next) // Pop first item from linked list
  182. // Notify reqRes listener if set
  183. if cb := reqres.GetCallback(); cb != nil {
  184. cb(res)
  185. }
  186. // Notify client listener if set
  187. if cli.resCb != nil {
  188. cli.resCb(reqres.Request, res)
  189. }
  190. return nil
  191. }
  192. //----------------------------------------
  193. func (cli *socketClient) EchoAsync(msg string) *ReqRes {
  194. return cli.queueRequest(types.ToRequestEcho(msg))
  195. }
  196. func (cli *socketClient) FlushAsync() *ReqRes {
  197. return cli.queueRequest(types.ToRequestFlush())
  198. }
  199. func (cli *socketClient) InfoAsync() *ReqRes {
  200. return cli.queueRequest(types.ToRequestInfo())
  201. }
  202. func (cli *socketClient) SetOptionAsync(key string, value string) *ReqRes {
  203. return cli.queueRequest(types.ToRequestSetOption(key, value))
  204. }
  205. func (cli *socketClient) DeliverTxAsync(tx []byte) *ReqRes {
  206. return cli.queueRequest(types.ToRequestDeliverTx(tx))
  207. }
  208. func (cli *socketClient) CheckTxAsync(tx []byte) *ReqRes {
  209. return cli.queueRequest(types.ToRequestCheckTx(tx))
  210. }
  211. func (cli *socketClient) QueryAsync(reqQuery types.RequestQuery) *ReqRes {
  212. return cli.queueRequest(types.ToRequestQuery(reqQuery))
  213. }
  214. func (cli *socketClient) CommitAsync() *ReqRes {
  215. return cli.queueRequest(types.ToRequestCommit())
  216. }
  217. func (cli *socketClient) InitChainAsync(validators []*types.Validator) *ReqRes {
  218. return cli.queueRequest(types.ToRequestInitChain(validators))
  219. }
  220. func (cli *socketClient) BeginBlockAsync(hash []byte, header *types.Header) *ReqRes {
  221. return cli.queueRequest(types.ToRequestBeginBlock(hash, header))
  222. }
  223. func (cli *socketClient) EndBlockAsync(height uint64) *ReqRes {
  224. return cli.queueRequest(types.ToRequestEndBlock(height))
  225. }
  226. //----------------------------------------
  227. func (cli *socketClient) EchoSync(msg string) (res types.Result) {
  228. reqres := cli.queueRequest(types.ToRequestEcho(msg))
  229. cli.FlushSync()
  230. if err := cli.Error(); err != nil {
  231. return types.ErrInternalError.SetLog(err.Error())
  232. }
  233. resp := reqres.Response.GetEcho()
  234. return types.Result{Code: OK, Data: []byte(resp.Message)}
  235. }
  236. func (cli *socketClient) FlushSync() error {
  237. reqRes := cli.queueRequest(types.ToRequestFlush())
  238. if err := cli.Error(); err != nil {
  239. return types.ErrInternalError.SetLog(err.Error())
  240. }
  241. reqRes.Wait() // NOTE: if we don't flush the queue, its possible to get stuck here
  242. return cli.Error()
  243. }
  244. func (cli *socketClient) InfoSync() (resInfo types.ResponseInfo, err error) {
  245. reqres := cli.queueRequest(types.ToRequestInfo())
  246. cli.FlushSync()
  247. if err := cli.Error(); err != nil {
  248. return resInfo, err
  249. }
  250. if resInfo_ := reqres.Response.GetInfo(); resInfo_ != nil {
  251. return *resInfo_, nil
  252. }
  253. return resInfo, nil
  254. }
  255. func (cli *socketClient) SetOptionSync(key string, value string) (res types.Result) {
  256. reqres := cli.queueRequest(types.ToRequestSetOption(key, value))
  257. cli.FlushSync()
  258. if err := cli.Error(); err != nil {
  259. return types.ErrInternalError.SetLog(err.Error())
  260. }
  261. resp := reqres.Response.GetSetOption()
  262. return types.Result{Code: OK, Data: nil, Log: resp.Log}
  263. }
  264. func (cli *socketClient) DeliverTxSync(tx []byte) (res types.Result) {
  265. reqres := cli.queueRequest(types.ToRequestDeliverTx(tx))
  266. cli.FlushSync()
  267. if err := cli.Error(); err != nil {
  268. return types.ErrInternalError.SetLog(err.Error())
  269. }
  270. resp := reqres.Response.GetDeliverTx()
  271. return types.Result{Code: resp.Code, Data: resp.Data, Log: resp.Log}
  272. }
  273. func (cli *socketClient) CheckTxSync(tx []byte) (res types.Result) {
  274. reqres := cli.queueRequest(types.ToRequestCheckTx(tx))
  275. cli.FlushSync()
  276. if err := cli.Error(); err != nil {
  277. return types.ErrInternalError.SetLog(err.Error())
  278. }
  279. resp := reqres.Response.GetCheckTx()
  280. return types.Result{Code: resp.Code, Data: resp.Data, Log: resp.Log}
  281. }
  282. func (cli *socketClient) QuerySync(reqQuery types.RequestQuery) (resQuery types.ResponseQuery, err error) {
  283. reqres := cli.queueRequest(types.ToRequestQuery(reqQuery))
  284. cli.FlushSync()
  285. if err := cli.Error(); err != nil {
  286. return resQuery, err
  287. }
  288. if resQuery_ := reqres.Response.GetQuery(); resQuery_ != nil {
  289. return *resQuery_, nil
  290. }
  291. return resQuery, nil
  292. }
  293. func (cli *socketClient) CommitSync() (res types.Result) {
  294. reqres := cli.queueRequest(types.ToRequestCommit())
  295. cli.FlushSync()
  296. if err := cli.Error(); err != nil {
  297. return types.ErrInternalError.SetLog(err.Error())
  298. }
  299. resp := reqres.Response.GetCommit()
  300. return types.Result{Code: resp.Code, Data: resp.Data, Log: resp.Log}
  301. }
  302. func (cli *socketClient) InitChainSync(validators []*types.Validator) (err error) {
  303. cli.queueRequest(types.ToRequestInitChain(validators))
  304. cli.FlushSync()
  305. if err := cli.Error(); err != nil {
  306. return err
  307. }
  308. return nil
  309. }
  310. func (cli *socketClient) BeginBlockSync(hash []byte, header *types.Header) (err error) {
  311. cli.queueRequest(types.ToRequestBeginBlock(hash, header))
  312. cli.FlushSync()
  313. if err := cli.Error(); err != nil {
  314. return err
  315. }
  316. return nil
  317. }
  318. func (cli *socketClient) EndBlockSync(height uint64) (resEndBlock types.ResponseEndBlock, err error) {
  319. reqres := cli.queueRequest(types.ToRequestEndBlock(height))
  320. cli.FlushSync()
  321. if err := cli.Error(); err != nil {
  322. return resEndBlock, err
  323. }
  324. if blk := reqres.Response.GetEndBlock(); blk != nil {
  325. return *blk, nil
  326. }
  327. return resEndBlock, nil
  328. }
  329. //----------------------------------------
  330. func (cli *socketClient) queueRequest(req *types.Request) *ReqRes {
  331. reqres := NewReqRes(req)
  332. // TODO: set cli.err if reqQueue times out
  333. cli.reqQueue <- reqres
  334. // Maybe auto-flush, or unset auto-flush
  335. switch req.Value.(type) {
  336. case *types.Request_Flush:
  337. cli.flushTimer.Unset()
  338. default:
  339. cli.flushTimer.Set()
  340. }
  341. return reqres
  342. }
  343. func (cli *socketClient) flushQueue() {
  344. LOOP:
  345. for {
  346. select {
  347. case reqres := <-cli.reqQueue:
  348. reqres.Done()
  349. default:
  350. break LOOP
  351. }
  352. }
  353. }
  354. //----------------------------------------
  355. func resMatchesReq(req *types.Request, res *types.Response) (ok bool) {
  356. switch req.Value.(type) {
  357. case *types.Request_Echo:
  358. _, ok = res.Value.(*types.Response_Echo)
  359. case *types.Request_Flush:
  360. _, ok = res.Value.(*types.Response_Flush)
  361. case *types.Request_Info:
  362. _, ok = res.Value.(*types.Response_Info)
  363. case *types.Request_SetOption:
  364. _, ok = res.Value.(*types.Response_SetOption)
  365. case *types.Request_DeliverTx:
  366. _, ok = res.Value.(*types.Response_DeliverTx)
  367. case *types.Request_CheckTx:
  368. _, ok = res.Value.(*types.Response_CheckTx)
  369. case *types.Request_Commit:
  370. _, ok = res.Value.(*types.Response_Commit)
  371. case *types.Request_Query:
  372. _, ok = res.Value.(*types.Response_Query)
  373. case *types.Request_InitChain:
  374. _, ok = res.Value.(*types.Response_InitChain)
  375. case *types.Request_BeginBlock:
  376. _, ok = res.Value.(*types.Response_BeginBlock)
  377. case *types.Request_EndBlock:
  378. _, ok = res.Value.(*types.Response_EndBlock)
  379. }
  380. return ok
  381. }