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.

439 lines
11 KiB

9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
  1. package tmspcli
  2. import (
  3. "bufio"
  4. "container/list"
  5. "errors"
  6. "fmt"
  7. "net"
  8. "reflect"
  9. "sync"
  10. "time"
  11. . "github.com/tendermint/go-common"
  12. "github.com/tendermint/tmsp/types"
  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. QuitService
  26. reqQueue chan *ReqRes
  27. flushTimer *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: NewThrottleTimer("socketClient", flushThrottleMS),
  40. mustConnect: mustConnect,
  41. addr: addr,
  42. reqSent: list.New(),
  43. resCb: nil,
  44. }
  45. cli.QuitService = *NewQuitService(nil, "socketClient", cli)
  46. _, err := cli.Start() // Just start it, it's confusing for callers to remember to start.
  47. return cli, err
  48. }
  49. func (cli *socketClient) OnStart() error {
  50. cli.QuitService.OnStart()
  51. var err error
  52. var conn net.Conn
  53. RETRY_LOOP:
  54. for {
  55. conn, err = Connect(cli.addr)
  56. if err != nil {
  57. if cli.mustConnect {
  58. return err
  59. } else {
  60. log.Warn(Fmt("tmsp.socketClient failed to connect to %v. Retrying...", cli.addr))
  61. time.Sleep(time.Second * 3)
  62. continue RETRY_LOOP
  63. }
  64. }
  65. cli.conn = conn
  66. go cli.sendRequestsRoutine(conn)
  67. go cli.recvResponseRoutine(conn)
  68. return nil
  69. }
  70. return nil // never happens
  71. }
  72. func (cli *socketClient) OnStop() {
  73. cli.QuitService.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. log.Warn(Fmt("Stopping tmsp.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.QuitService.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. // log.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. // log.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) AppendTxAsync(tx []byte) *ReqRes {
  206. return cli.queueRequest(types.ToRequestAppendTx(tx))
  207. }
  208. func (cli *socketClient) CheckTxAsync(tx []byte) *ReqRes {
  209. return cli.queueRequest(types.ToRequestCheckTx(tx))
  210. }
  211. func (cli *socketClient) QueryAsync(query []byte) *ReqRes {
  212. return cli.queueRequest(types.ToRequestQuery(query))
  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(height uint64) *ReqRes {
  221. return cli.queueRequest(types.ToRequestBeginBlock(height))
  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), Log: LOG}
  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() (res types.Result) {
  245. reqres := cli.queueRequest(types.ToRequestInfo())
  246. cli.FlushSync()
  247. if err := cli.Error(); err != nil {
  248. return types.ErrInternalError.SetLog(err.Error())
  249. }
  250. resp := reqres.Response.GetInfo()
  251. return types.Result{Code: OK, Data: []byte(resp.Info), Log: LOG}
  252. }
  253. func (cli *socketClient) SetOptionSync(key string, value string) (res types.Result) {
  254. reqres := cli.queueRequest(types.ToRequestSetOption(key, value))
  255. cli.FlushSync()
  256. if err := cli.Error(); err != nil {
  257. return types.ErrInternalError.SetLog(err.Error())
  258. }
  259. resp := reqres.Response.GetSetOption()
  260. return types.Result{Code: OK, Data: nil, Log: resp.Log}
  261. }
  262. func (cli *socketClient) AppendTxSync(tx []byte) (res types.Result) {
  263. reqres := cli.queueRequest(types.ToRequestAppendTx(tx))
  264. cli.FlushSync()
  265. if err := cli.Error(); err != nil {
  266. return types.ErrInternalError.SetLog(err.Error())
  267. }
  268. resp := reqres.Response.GetAppendTx()
  269. return types.Result{Code: resp.Code, Data: resp.Data, Log: resp.Log}
  270. }
  271. func (cli *socketClient) CheckTxSync(tx []byte) (res types.Result) {
  272. reqres := cli.queueRequest(types.ToRequestCheckTx(tx))
  273. cli.FlushSync()
  274. if err := cli.Error(); err != nil {
  275. return types.ErrInternalError.SetLog(err.Error())
  276. }
  277. resp := reqres.Response.GetCheckTx()
  278. return types.Result{Code: resp.Code, Data: resp.Data, Log: resp.Log}
  279. }
  280. func (cli *socketClient) QuerySync(query []byte) (res types.Result) {
  281. reqres := cli.queueRequest(types.ToRequestQuery(query))
  282. cli.FlushSync()
  283. if err := cli.Error(); err != nil {
  284. return types.ErrInternalError.SetLog(err.Error())
  285. }
  286. resp := reqres.Response.GetQuery()
  287. return types.Result{Code: resp.Code, Data: resp.Data, Log: resp.Log}
  288. }
  289. func (cli *socketClient) CommitSync() (res types.Result) {
  290. reqres := cli.queueRequest(types.ToRequestCommit())
  291. cli.FlushSync()
  292. if err := cli.Error(); err != nil {
  293. return types.ErrInternalError.SetLog(err.Error())
  294. }
  295. resp := reqres.Response.GetCommit()
  296. return types.Result{Code: resp.Code, Data: resp.Data, Log: resp.Log}
  297. }
  298. func (cli *socketClient) InitChainSync(validators []*types.Validator) (err error) {
  299. cli.queueRequest(types.ToRequestInitChain(validators))
  300. cli.FlushSync()
  301. if err := cli.Error(); err != nil {
  302. return err
  303. }
  304. return nil
  305. }
  306. func (cli *socketClient) BeginBlockSync(height uint64) (err error) {
  307. cli.queueRequest(types.ToRequestBeginBlock(height))
  308. cli.FlushSync()
  309. if err := cli.Error(); err != nil {
  310. return err
  311. }
  312. return nil
  313. }
  314. func (cli *socketClient) EndBlockSync(height uint64) (validators []*types.Validator, err error) {
  315. reqres := cli.queueRequest(types.ToRequestEndBlock(height))
  316. cli.FlushSync()
  317. if err := cli.Error(); err != nil {
  318. return nil, err
  319. }
  320. return reqres.Response.GetEndBlock().Diffs, nil
  321. }
  322. //----------------------------------------
  323. func (cli *socketClient) queueRequest(req *types.Request) *ReqRes {
  324. reqres := NewReqRes(req)
  325. // TODO: set cli.err if reqQueue times out
  326. cli.reqQueue <- reqres
  327. // Maybe auto-flush, or unset auto-flush
  328. switch req.Value.(type) {
  329. case *types.Request_Flush:
  330. cli.flushTimer.Unset()
  331. default:
  332. cli.flushTimer.Set()
  333. }
  334. return reqres
  335. }
  336. func (cli *socketClient) flushQueue() {
  337. LOOP:
  338. for {
  339. select {
  340. case reqres := <-cli.reqQueue:
  341. reqres.Done()
  342. default:
  343. break LOOP
  344. }
  345. }
  346. }
  347. //----------------------------------------
  348. func resMatchesReq(req *types.Request, res *types.Response) (ok bool) {
  349. switch req.Value.(type) {
  350. case *types.Request_Echo:
  351. _, ok = res.Value.(*types.Response_Echo)
  352. case *types.Request_Flush:
  353. _, ok = res.Value.(*types.Response_Flush)
  354. case *types.Request_Info:
  355. _, ok = res.Value.(*types.Response_Info)
  356. case *types.Request_SetOption:
  357. _, ok = res.Value.(*types.Response_SetOption)
  358. case *types.Request_AppendTx:
  359. _, ok = res.Value.(*types.Response_AppendTx)
  360. case *types.Request_CheckTx:
  361. _, ok = res.Value.(*types.Response_CheckTx)
  362. case *types.Request_Commit:
  363. _, ok = res.Value.(*types.Response_Commit)
  364. case *types.Request_Query:
  365. _, ok = res.Value.(*types.Response_Query)
  366. case *types.Request_InitChain:
  367. _, ok = res.Value.(*types.Response_InitChain)
  368. case *types.Request_EndBlock:
  369. _, ok = res.Value.(*types.Response_EndBlock)
  370. }
  371. return ok
  372. }