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.

342 lines
9.6 KiB

8 years ago
8 years ago
8 years ago
9 years ago
8 years ago
8 years ago
8 years ago
8 years ago
9 years ago
9 years ago
9 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
  1. package abcicli
  2. import (
  3. "fmt"
  4. "net"
  5. "sync"
  6. "time"
  7. context "golang.org/x/net/context"
  8. grpc "google.golang.org/grpc"
  9. "github.com/tendermint/abci/types"
  10. cmn "github.com/tendermint/tmlibs/common"
  11. )
  12. // A stripped copy of the remoteClient that makes
  13. // synchronous calls using grpc
  14. type grpcClient struct {
  15. cmn.BaseService
  16. mustConnect bool
  17. client types.ABCIApplicationClient
  18. mtx sync.Mutex
  19. addr string
  20. err error
  21. resCb func(*types.Request, *types.Response) // listens to all callbacks
  22. }
  23. func NewGRPCClient(addr string, mustConnect bool) (*grpcClient, error) {
  24. cli := &grpcClient{
  25. addr: addr,
  26. mustConnect: mustConnect,
  27. }
  28. cli.BaseService = *cmn.NewBaseService(nil, "grpcClient", cli)
  29. _, err := cli.Start() // Just start it, it's confusing for callers to remember to start.
  30. return cli, err
  31. }
  32. func dialerFunc(addr string, timeout time.Duration) (net.Conn, error) {
  33. return cmn.Connect(addr)
  34. }
  35. func (cli *grpcClient) OnStart() error {
  36. cli.BaseService.OnStart()
  37. RETRY_LOOP:
  38. for {
  39. conn, err := grpc.Dial(cli.addr, grpc.WithInsecure(), grpc.WithDialer(dialerFunc))
  40. if err != nil {
  41. if cli.mustConnect {
  42. return err
  43. }
  44. log.Warn(fmt.Sprintf("abci.grpcClient failed to connect to %v. Retrying...\n", cli.addr))
  45. time.Sleep(time.Second * 3)
  46. continue RETRY_LOOP
  47. }
  48. client := types.NewABCIApplicationClient(conn)
  49. ENSURE_CONNECTED:
  50. for {
  51. _, err := client.Echo(context.Background(), &types.RequestEcho{"hello"}, grpc.FailFast(true))
  52. if err == nil {
  53. break ENSURE_CONNECTED
  54. }
  55. time.Sleep(time.Second)
  56. }
  57. cli.client = client
  58. return nil
  59. }
  60. }
  61. func (cli *grpcClient) OnStop() {
  62. cli.BaseService.OnStop()
  63. cli.mtx.Lock()
  64. defer cli.mtx.Unlock()
  65. // TODO: how to close conn? its not a net.Conn and grpc doesn't expose a Close()
  66. /*if cli.conn != nil {
  67. cli.conn.Close()
  68. }*/
  69. }
  70. func (cli *grpcClient) StopForError(err error) {
  71. cli.mtx.Lock()
  72. if !cli.IsRunning() {
  73. return
  74. }
  75. if cli.err == nil {
  76. cli.err = err
  77. }
  78. cli.mtx.Unlock()
  79. log.Warn(fmt.Sprintf("Stopping abci.grpcClient for error: %v", err.Error()))
  80. cli.Stop()
  81. }
  82. func (cli *grpcClient) Error() error {
  83. cli.mtx.Lock()
  84. defer cli.mtx.Unlock()
  85. return cli.err
  86. }
  87. // Set listener for all responses
  88. // NOTE: callback may get internally generated flush responses.
  89. func (cli *grpcClient) SetResponseCallback(resCb Callback) {
  90. cli.mtx.Lock()
  91. defer cli.mtx.Unlock()
  92. cli.resCb = resCb
  93. }
  94. //----------------------------------------
  95. // GRPC calls are synchronous, but some callbacks expect to be called asynchronously
  96. // (eg. the mempool expects to be able to lock to remove bad txs from cache).
  97. // To accomodate, we finish each call in its own go-routine,
  98. // which is expensive, but easy - if you want something better, use the socket protocol!
  99. // maybe one day, if people really want it, we use grpc streams,
  100. // but hopefully not :D
  101. func (cli *grpcClient) EchoAsync(msg string) *ReqRes {
  102. req := types.ToRequestEcho(msg)
  103. res, err := cli.client.Echo(context.Background(), req.GetEcho(), grpc.FailFast(true))
  104. if err != nil {
  105. cli.StopForError(err)
  106. }
  107. return cli.finishAsyncCall(req, &types.Response{&types.Response_Echo{res}})
  108. }
  109. func (cli *grpcClient) FlushAsync() *ReqRes {
  110. req := types.ToRequestFlush()
  111. res, err := cli.client.Flush(context.Background(), req.GetFlush(), grpc.FailFast(true))
  112. if err != nil {
  113. cli.StopForError(err)
  114. }
  115. return cli.finishAsyncCall(req, &types.Response{&types.Response_Flush{res}})
  116. }
  117. func (cli *grpcClient) InfoAsync() *ReqRes {
  118. req := types.ToRequestInfo()
  119. res, err := cli.client.Info(context.Background(), req.GetInfo(), grpc.FailFast(true))
  120. if err != nil {
  121. cli.StopForError(err)
  122. }
  123. return cli.finishAsyncCall(req, &types.Response{&types.Response_Info{res}})
  124. }
  125. func (cli *grpcClient) SetOptionAsync(key string, value string) *ReqRes {
  126. req := types.ToRequestSetOption(key, value)
  127. res, err := cli.client.SetOption(context.Background(), req.GetSetOption(), grpc.FailFast(true))
  128. if err != nil {
  129. cli.StopForError(err)
  130. }
  131. return cli.finishAsyncCall(req, &types.Response{&types.Response_SetOption{res}})
  132. }
  133. func (cli *grpcClient) DeliverTxAsync(tx []byte) *ReqRes {
  134. req := types.ToRequestDeliverTx(tx)
  135. res, err := cli.client.DeliverTx(context.Background(), req.GetDeliverTx(), grpc.FailFast(true))
  136. if err != nil {
  137. cli.StopForError(err)
  138. }
  139. return cli.finishAsyncCall(req, &types.Response{&types.Response_DeliverTx{res}})
  140. }
  141. func (cli *grpcClient) CheckTxAsync(tx []byte) *ReqRes {
  142. req := types.ToRequestCheckTx(tx)
  143. res, err := cli.client.CheckTx(context.Background(), req.GetCheckTx(), grpc.FailFast(true))
  144. if err != nil {
  145. cli.StopForError(err)
  146. }
  147. return cli.finishAsyncCall(req, &types.Response{&types.Response_CheckTx{res}})
  148. }
  149. func (cli *grpcClient) QueryAsync(reqQuery types.RequestQuery) *ReqRes {
  150. req := types.ToRequestQuery(reqQuery)
  151. res, err := cli.client.Query(context.Background(), req.GetQuery(), grpc.FailFast(true))
  152. if err != nil {
  153. cli.StopForError(err)
  154. }
  155. return cli.finishAsyncCall(req, &types.Response{&types.Response_Query{res}})
  156. }
  157. func (cli *grpcClient) CommitAsync() *ReqRes {
  158. req := types.ToRequestCommit()
  159. res, err := cli.client.Commit(context.Background(), req.GetCommit(), grpc.FailFast(true))
  160. if err != nil {
  161. cli.StopForError(err)
  162. }
  163. return cli.finishAsyncCall(req, &types.Response{&types.Response_Commit{res}})
  164. }
  165. func (cli *grpcClient) InitChainAsync(validators []*types.Validator) *ReqRes {
  166. req := types.ToRequestInitChain(validators)
  167. res, err := cli.client.InitChain(context.Background(), req.GetInitChain(), grpc.FailFast(true))
  168. if err != nil {
  169. cli.StopForError(err)
  170. }
  171. return cli.finishAsyncCall(req, &types.Response{&types.Response_InitChain{res}})
  172. }
  173. func (cli *grpcClient) BeginBlockAsync(hash []byte, header *types.Header) *ReqRes {
  174. req := types.ToRequestBeginBlock(hash, header)
  175. res, err := cli.client.BeginBlock(context.Background(), req.GetBeginBlock(), grpc.FailFast(true))
  176. if err != nil {
  177. cli.StopForError(err)
  178. }
  179. return cli.finishAsyncCall(req, &types.Response{&types.Response_BeginBlock{res}})
  180. }
  181. func (cli *grpcClient) EndBlockAsync(height uint64) *ReqRes {
  182. req := types.ToRequestEndBlock(height)
  183. res, err := cli.client.EndBlock(context.Background(), req.GetEndBlock(), grpc.FailFast(true))
  184. if err != nil {
  185. cli.StopForError(err)
  186. }
  187. return cli.finishAsyncCall(req, &types.Response{&types.Response_EndBlock{res}})
  188. }
  189. func (cli *grpcClient) finishAsyncCall(req *types.Request, res *types.Response) *ReqRes {
  190. reqres := NewReqRes(req)
  191. reqres.Response = res // Set response
  192. reqres.Done() // Release waiters
  193. reqres.SetDone() // so reqRes.SetCallback will run the callback
  194. // go routine for callbacks
  195. go func() {
  196. // Notify reqRes listener if set
  197. if cb := reqres.GetCallback(); cb != nil {
  198. cb(res)
  199. }
  200. // Notify client listener if set
  201. if cli.resCb != nil {
  202. cli.resCb(reqres.Request, res)
  203. }
  204. }()
  205. return reqres
  206. }
  207. func (cli *grpcClient) checkErrGetResult() types.Result {
  208. if err := cli.Error(); err != nil {
  209. // StopForError should already have been called if error is set
  210. return types.ErrInternalError.SetLog(err.Error())
  211. }
  212. return types.Result{}
  213. }
  214. //----------------------------------------
  215. func (cli *grpcClient) EchoSync(msg string) (res types.Result) {
  216. reqres := cli.EchoAsync(msg)
  217. if res := cli.checkErrGetResult(); res.IsErr() {
  218. return res
  219. }
  220. resp := reqres.Response.GetEcho()
  221. return types.NewResultOK([]byte(resp.Message), "")
  222. }
  223. func (cli *grpcClient) FlushSync() error {
  224. return nil
  225. }
  226. func (cli *grpcClient) InfoSync() (resInfo types.ResponseInfo, err error) {
  227. reqres := cli.InfoAsync()
  228. if err = cli.Error(); err != nil {
  229. return resInfo, err
  230. }
  231. if info := reqres.Response.GetInfo(); info != nil {
  232. return *info, nil
  233. }
  234. return resInfo, nil
  235. }
  236. func (cli *grpcClient) SetOptionSync(key string, value string) (res types.Result) {
  237. reqres := cli.SetOptionAsync(key, value)
  238. if res := cli.checkErrGetResult(); res.IsErr() {
  239. return res
  240. }
  241. resp := reqres.Response.GetSetOption()
  242. return types.Result{Code: OK, Data: nil, Log: resp.Log}
  243. }
  244. func (cli *grpcClient) DeliverTxSync(tx []byte) (res types.Result) {
  245. reqres := cli.DeliverTxAsync(tx)
  246. if res := cli.checkErrGetResult(); res.IsErr() {
  247. return res
  248. }
  249. resp := reqres.Response.GetDeliverTx()
  250. return types.Result{Code: resp.Code, Data: resp.Data, Log: resp.Log}
  251. }
  252. func (cli *grpcClient) CheckTxSync(tx []byte) (res types.Result) {
  253. reqres := cli.CheckTxAsync(tx)
  254. if res := cli.checkErrGetResult(); res.IsErr() {
  255. return res
  256. }
  257. resp := reqres.Response.GetCheckTx()
  258. return types.Result{Code: resp.Code, Data: resp.Data, Log: resp.Log}
  259. }
  260. func (cli *grpcClient) QuerySync(reqQuery types.RequestQuery) (resQuery types.ResponseQuery, err error) {
  261. reqres := cli.QueryAsync(reqQuery)
  262. if err = cli.Error(); err != nil {
  263. return resQuery, err
  264. }
  265. if resQuery_ := reqres.Response.GetQuery(); resQuery_ != nil {
  266. return *resQuery_, nil
  267. }
  268. return resQuery, nil
  269. }
  270. func (cli *grpcClient) CommitSync() (res types.Result) {
  271. reqres := cli.CommitAsync()
  272. if res := cli.checkErrGetResult(); res.IsErr() {
  273. return res
  274. }
  275. resp := reqres.Response.GetCommit()
  276. return types.Result{Code: resp.Code, Data: resp.Data, Log: resp.Log}
  277. }
  278. func (cli *grpcClient) InitChainSync(validators []*types.Validator) (err error) {
  279. cli.InitChainAsync(validators)
  280. return cli.Error()
  281. }
  282. func (cli *grpcClient) BeginBlockSync(hash []byte, header *types.Header) (err error) {
  283. cli.BeginBlockAsync(hash, header)
  284. return cli.Error()
  285. }
  286. func (cli *grpcClient) EndBlockSync(height uint64) (resEndBlock types.ResponseEndBlock, err error) {
  287. reqres := cli.EndBlockAsync(height)
  288. if err := cli.Error(); err != nil {
  289. return resEndBlock, err
  290. }
  291. if blk := reqres.Response.GetEndBlock(); blk != nil {
  292. return *blk, nil
  293. }
  294. return resEndBlock, nil
  295. }