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.

444 lines
11 KiB

9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 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. BaseService
  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.BaseService = *NewBaseService(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.BaseService.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.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. 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.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. // 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(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), 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() (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. } else {
  253. return resInfo, nil
  254. }
  255. }
  256. func (cli *socketClient) SetOptionSync(key string, value string) (res types.Result) {
  257. reqres := cli.queueRequest(types.ToRequestSetOption(key, value))
  258. cli.FlushSync()
  259. if err := cli.Error(); err != nil {
  260. return types.ErrInternalError.SetLog(err.Error())
  261. }
  262. resp := reqres.Response.GetSetOption()
  263. return types.Result{Code: OK, Data: nil, Log: resp.Log}
  264. }
  265. func (cli *socketClient) AppendTxSync(tx []byte) (res types.Result) {
  266. reqres := cli.queueRequest(types.ToRequestAppendTx(tx))
  267. cli.FlushSync()
  268. if err := cli.Error(); err != nil {
  269. return types.ErrInternalError.SetLog(err.Error())
  270. }
  271. resp := reqres.Response.GetAppendTx()
  272. return types.Result{Code: resp.Code, Data: resp.Data, Log: resp.Log}
  273. }
  274. func (cli *socketClient) CheckTxSync(tx []byte) (res types.Result) {
  275. reqres := cli.queueRequest(types.ToRequestCheckTx(tx))
  276. cli.FlushSync()
  277. if err := cli.Error(); err != nil {
  278. return types.ErrInternalError.SetLog(err.Error())
  279. }
  280. resp := reqres.Response.GetCheckTx()
  281. return types.Result{Code: resp.Code, Data: resp.Data, Log: resp.Log}
  282. }
  283. func (cli *socketClient) QuerySync(query []byte) (res types.Result) {
  284. reqres := cli.queueRequest(types.ToRequestQuery(query))
  285. cli.FlushSync()
  286. if err := cli.Error(); err != nil {
  287. return types.ErrInternalError.SetLog(err.Error())
  288. }
  289. resp := reqres.Response.GetQuery()
  290. return types.Result{Code: resp.Code, Data: resp.Data, Log: resp.Log}
  291. }
  292. func (cli *socketClient) CommitSync() (res types.Result) {
  293. reqres := cli.queueRequest(types.ToRequestCommit())
  294. cli.FlushSync()
  295. if err := cli.Error(); err != nil {
  296. return types.ErrInternalError.SetLog(err.Error())
  297. }
  298. resp := reqres.Response.GetCommit()
  299. return types.Result{Code: resp.Code, Data: resp.Data, Log: resp.Log}
  300. }
  301. func (cli *socketClient) InitChainSync(validators []*types.Validator) (err error) {
  302. cli.queueRequest(types.ToRequestInitChain(validators))
  303. cli.FlushSync()
  304. if err := cli.Error(); err != nil {
  305. return err
  306. }
  307. return nil
  308. }
  309. func (cli *socketClient) BeginBlockSync(hash []byte, header *types.Header) (err error) {
  310. cli.queueRequest(types.ToRequestBeginBlock(hash, header))
  311. cli.FlushSync()
  312. if err := cli.Error(); err != nil {
  313. return err
  314. }
  315. return nil
  316. }
  317. func (cli *socketClient) EndBlockSync(height uint64) (validators []*types.Validator, err error) {
  318. reqres := cli.queueRequest(types.ToRequestEndBlock(height))
  319. cli.FlushSync()
  320. if err := cli.Error(); err != nil {
  321. return nil, err
  322. }
  323. return reqres.Response.GetEndBlock().Diffs, nil
  324. }
  325. //----------------------------------------
  326. func (cli *socketClient) queueRequest(req *types.Request) *ReqRes {
  327. reqres := NewReqRes(req)
  328. // TODO: set cli.err if reqQueue times out
  329. cli.reqQueue <- reqres
  330. // Maybe auto-flush, or unset auto-flush
  331. switch req.Value.(type) {
  332. case *types.Request_Flush:
  333. cli.flushTimer.Unset()
  334. default:
  335. cli.flushTimer.Set()
  336. }
  337. return reqres
  338. }
  339. func (cli *socketClient) flushQueue() {
  340. LOOP:
  341. for {
  342. select {
  343. case reqres := <-cli.reqQueue:
  344. reqres.Done()
  345. default:
  346. break LOOP
  347. }
  348. }
  349. }
  350. //----------------------------------------
  351. func resMatchesReq(req *types.Request, res *types.Response) (ok bool) {
  352. switch req.Value.(type) {
  353. case *types.Request_Echo:
  354. _, ok = res.Value.(*types.Response_Echo)
  355. case *types.Request_Flush:
  356. _, ok = res.Value.(*types.Response_Flush)
  357. case *types.Request_Info:
  358. _, ok = res.Value.(*types.Response_Info)
  359. case *types.Request_SetOption:
  360. _, ok = res.Value.(*types.Response_SetOption)
  361. case *types.Request_AppendTx:
  362. _, ok = res.Value.(*types.Response_AppendTx)
  363. case *types.Request_CheckTx:
  364. _, ok = res.Value.(*types.Response_CheckTx)
  365. case *types.Request_Commit:
  366. _, ok = res.Value.(*types.Response_Commit)
  367. case *types.Request_Query:
  368. _, ok = res.Value.(*types.Response_Query)
  369. case *types.Request_InitChain:
  370. _, ok = res.Value.(*types.Response_InitChain)
  371. case *types.Request_BeginBlock:
  372. _, ok = res.Value.(*types.Response_BeginBlock)
  373. case *types.Request_EndBlock:
  374. _, ok = res.Value.(*types.Response_EndBlock)
  375. }
  376. return ok
  377. }