client_test.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587
  1. // Copyright 2016 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. package rpc
  17. import (
  18. "context"
  19. "fmt"
  20. "math/rand"
  21. "net"
  22. "net/http"
  23. "net/http/httptest"
  24. "os"
  25. "reflect"
  26. "runtime"
  27. "sync"
  28. "testing"
  29. "time"
  30. "github.com/davecgh/go-spew/spew"
  31. "github.com/ethereum/go-ethereum/log"
  32. )
  33. func TestClientRequest(t *testing.T) {
  34. server := newTestServer()
  35. defer server.Stop()
  36. client := DialInProc(server)
  37. defer client.Close()
  38. var resp echoResult
  39. if err := client.Call(&resp, "test_echo", "hello", 10, &echoArgs{"world"}); err != nil {
  40. t.Fatal(err)
  41. }
  42. if !reflect.DeepEqual(resp, echoResult{"hello", 10, &echoArgs{"world"}}) {
  43. t.Errorf("incorrect result %#v", resp)
  44. }
  45. }
  46. func TestClientResponseType(t *testing.T) {
  47. server := newTestServer()
  48. defer server.Stop()
  49. client := DialInProc(server)
  50. defer client.Close()
  51. if err := client.Call(nil, "test_echo", "hello", 10, &echoArgs{"world"}); err != nil {
  52. t.Errorf("Passing nil as result should be fine, but got an error: %v", err)
  53. }
  54. var resultVar echoResult
  55. // Note: passing the var, not a ref
  56. err := client.Call(resultVar, "test_echo", "hello", 10, &echoArgs{"world"})
  57. if err == nil {
  58. t.Error("Passing a var as result should be an error")
  59. }
  60. }
  61. func TestClientBatchRequest(t *testing.T) {
  62. server := newTestServer()
  63. defer server.Stop()
  64. client := DialInProc(server)
  65. defer client.Close()
  66. batch := []BatchElem{
  67. {
  68. Method: "test_echo",
  69. Args: []interface{}{"hello", 10, &echoArgs{"world"}},
  70. Result: new(echoResult),
  71. },
  72. {
  73. Method: "test_echo",
  74. Args: []interface{}{"hello2", 11, &echoArgs{"world"}},
  75. Result: new(echoResult),
  76. },
  77. {
  78. Method: "no_such_method",
  79. Args: []interface{}{1, 2, 3},
  80. Result: new(int),
  81. },
  82. }
  83. if err := client.BatchCall(batch); err != nil {
  84. t.Fatal(err)
  85. }
  86. wantResult := []BatchElem{
  87. {
  88. Method: "test_echo",
  89. Args: []interface{}{"hello", 10, &echoArgs{"world"}},
  90. Result: &echoResult{"hello", 10, &echoArgs{"world"}},
  91. },
  92. {
  93. Method: "test_echo",
  94. Args: []interface{}{"hello2", 11, &echoArgs{"world"}},
  95. Result: &echoResult{"hello2", 11, &echoArgs{"world"}},
  96. },
  97. {
  98. Method: "no_such_method",
  99. Args: []interface{}{1, 2, 3},
  100. Result: new(int),
  101. Error: &jsonError{Code: -32601, Message: "the method no_such_method does not exist/is not available"},
  102. },
  103. }
  104. if !reflect.DeepEqual(batch, wantResult) {
  105. t.Errorf("batch results mismatch:\ngot %swant %s", spew.Sdump(batch), spew.Sdump(wantResult))
  106. }
  107. }
  108. func TestClientNotify(t *testing.T) {
  109. server := newTestServer()
  110. defer server.Stop()
  111. client := DialInProc(server)
  112. defer client.Close()
  113. if err := client.Notify(context.Background(), "test_echo", "hello", 10, &echoArgs{"world"}); err != nil {
  114. t.Fatal(err)
  115. }
  116. }
  117. // func TestClientCancelInproc(t *testing.T) { testClientCancel("inproc", t) }
  118. func TestClientCancelWebsocket(t *testing.T) { testClientCancel("ws", t) }
  119. func TestClientCancelHTTP(t *testing.T) { testClientCancel("http", t) }
  120. func TestClientCancelIPC(t *testing.T) { testClientCancel("ipc", t) }
  121. // This test checks that requests made through CallContext can be canceled by canceling
  122. // the context.
  123. func testClientCancel(transport string, t *testing.T) {
  124. // These tests take a lot of time, run them all at once.
  125. // You probably want to run with -parallel 1 or comment out
  126. // the call to t.Parallel if you enable the logging.
  127. t.Parallel()
  128. server := newTestServer()
  129. defer server.Stop()
  130. // What we want to achieve is that the context gets canceled
  131. // at various stages of request processing. The interesting cases
  132. // are:
  133. // - cancel during dial
  134. // - cancel while performing a HTTP request
  135. // - cancel while waiting for a response
  136. //
  137. // To trigger those, the times are chosen such that connections
  138. // are killed within the deadline for every other call (maxKillTimeout
  139. // is 2x maxCancelTimeout).
  140. //
  141. // Once a connection is dead, there is a fair chance it won't connect
  142. // successfully because the accept is delayed by 1s.
  143. maxContextCancelTimeout := 300 * time.Millisecond
  144. fl := &flakeyListener{
  145. maxAcceptDelay: 1 * time.Second,
  146. maxKillTimeout: 600 * time.Millisecond,
  147. }
  148. var client *Client
  149. switch transport {
  150. case "ws", "http":
  151. c, hs := httpTestClient(server, transport, fl)
  152. defer hs.Close()
  153. client = c
  154. case "ipc":
  155. c, l := ipcTestClient(server, fl)
  156. defer l.Close()
  157. client = c
  158. default:
  159. panic("unknown transport: " + transport)
  160. }
  161. // The actual test starts here.
  162. var (
  163. wg sync.WaitGroup
  164. nreqs = 10
  165. ncallers = 10
  166. )
  167. caller := func(index int) {
  168. defer wg.Done()
  169. for i := 0; i < nreqs; i++ {
  170. var (
  171. ctx context.Context
  172. cancel func()
  173. timeout = time.Duration(rand.Int63n(int64(maxContextCancelTimeout)))
  174. )
  175. if index < ncallers/2 {
  176. // For half of the callers, create a context without deadline
  177. // and cancel it later.
  178. ctx, cancel = context.WithCancel(context.Background())
  179. time.AfterFunc(timeout, cancel)
  180. } else {
  181. // For the other half, create a context with a deadline instead. This is
  182. // different because the context deadline is used to set the socket write
  183. // deadline.
  184. ctx, cancel = context.WithTimeout(context.Background(), timeout)
  185. }
  186. // Now perform a call with the context.
  187. // The key thing here is that no call will ever complete successfully.
  188. err := client.CallContext(ctx, nil, "test_block")
  189. switch {
  190. case err == nil:
  191. _, hasDeadline := ctx.Deadline()
  192. t.Errorf("no error for call with %v wait time (deadline: %v)", timeout, hasDeadline)
  193. // default:
  194. // t.Logf("got expected error with %v wait time: %v", timeout, err)
  195. }
  196. cancel()
  197. }
  198. }
  199. wg.Add(ncallers)
  200. for i := 0; i < ncallers; i++ {
  201. go caller(i)
  202. }
  203. wg.Wait()
  204. }
  205. func TestClientSubscribeInvalidArg(t *testing.T) {
  206. server := newTestServer()
  207. defer server.Stop()
  208. client := DialInProc(server)
  209. defer client.Close()
  210. check := func(shouldPanic bool, arg interface{}) {
  211. defer func() {
  212. err := recover()
  213. if shouldPanic && err == nil {
  214. t.Errorf("EthSubscribe should've panicked for %#v", arg)
  215. }
  216. if !shouldPanic && err != nil {
  217. t.Errorf("EthSubscribe shouldn't have panicked for %#v", arg)
  218. buf := make([]byte, 1024*1024)
  219. buf = buf[:runtime.Stack(buf, false)]
  220. t.Error(err)
  221. t.Error(string(buf))
  222. }
  223. }()
  224. client.EthSubscribe(context.Background(), arg, "foo_bar")
  225. }
  226. check(true, nil)
  227. check(true, 1)
  228. check(true, (chan int)(nil))
  229. check(true, make(<-chan int))
  230. check(false, make(chan int))
  231. check(false, make(chan<- int))
  232. }
  233. func TestClientSubscribe(t *testing.T) {
  234. server := newTestServer()
  235. defer server.Stop()
  236. client := DialInProc(server)
  237. defer client.Close()
  238. nc := make(chan int)
  239. count := 10
  240. sub, err := client.Subscribe(context.Background(), "nftest", nc, "someSubscription", count, 0)
  241. if err != nil {
  242. t.Fatal("can't subscribe:", err)
  243. }
  244. for i := 0; i < count; i++ {
  245. if val := <-nc; val != i {
  246. t.Fatalf("value mismatch: got %d, want %d", val, i)
  247. }
  248. }
  249. sub.Unsubscribe()
  250. select {
  251. case v := <-nc:
  252. t.Fatal("received value after unsubscribe:", v)
  253. case err := <-sub.Err():
  254. if err != nil {
  255. t.Fatalf("Err returned a non-nil error after explicit unsubscribe: %q", err)
  256. }
  257. case <-time.After(1 * time.Second):
  258. t.Fatalf("subscription not closed within 1s after unsubscribe")
  259. }
  260. }
  261. // In this test, the connection drops while Subscribe is waiting for a response.
  262. func TestClientSubscribeClose(t *testing.T) {
  263. server := newTestServer()
  264. service := &notificationTestService{
  265. gotHangSubscriptionReq: make(chan struct{}),
  266. unblockHangSubscription: make(chan struct{}),
  267. }
  268. if err := server.RegisterName("nftest2", service); err != nil {
  269. t.Fatal(err)
  270. }
  271. defer server.Stop()
  272. client := DialInProc(server)
  273. defer client.Close()
  274. var (
  275. nc = make(chan int)
  276. errc = make(chan error, 1)
  277. sub *ClientSubscription
  278. err error
  279. )
  280. go func() {
  281. sub, err = client.Subscribe(context.Background(), "nftest2", nc, "hangSubscription", 999)
  282. errc <- err
  283. }()
  284. <-service.gotHangSubscriptionReq
  285. client.Close()
  286. service.unblockHangSubscription <- struct{}{}
  287. select {
  288. case err := <-errc:
  289. if err == nil {
  290. t.Errorf("Subscribe returned nil error after Close")
  291. }
  292. if sub != nil {
  293. t.Error("Subscribe returned non-nil subscription after Close")
  294. }
  295. case <-time.After(1 * time.Second):
  296. t.Fatalf("Subscribe did not return within 1s after Close")
  297. }
  298. }
  299. // This test reproduces https://github.com/ethereum/go-ethereum/issues/17837 where the
  300. // client hangs during shutdown when Unsubscribe races with Client.Close.
  301. func TestClientCloseUnsubscribeRace(t *testing.T) {
  302. server := newTestServer()
  303. defer server.Stop()
  304. for i := 0; i < 20; i++ {
  305. client := DialInProc(server)
  306. nc := make(chan int)
  307. sub, err := client.Subscribe(context.Background(), "nftest", nc, "someSubscription", 3, 1)
  308. if err != nil {
  309. t.Fatal(err)
  310. }
  311. go client.Close()
  312. go sub.Unsubscribe()
  313. select {
  314. case <-sub.Err():
  315. case <-time.After(5 * time.Second):
  316. t.Fatal("subscription not closed within timeout")
  317. }
  318. }
  319. }
  320. // This test checks that Client doesn't lock up when a single subscriber
  321. // doesn't read subscription events.
  322. func TestClientNotificationStorm(t *testing.T) {
  323. server := newTestServer()
  324. defer server.Stop()
  325. doTest := func(count int, wantError bool) {
  326. client := DialInProc(server)
  327. defer client.Close()
  328. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  329. defer cancel()
  330. // Subscribe on the server. It will start sending many notifications
  331. // very quickly.
  332. nc := make(chan int)
  333. sub, err := client.Subscribe(ctx, "nftest", nc, "someSubscription", count, 0)
  334. if err != nil {
  335. t.Fatal("can't subscribe:", err)
  336. }
  337. defer sub.Unsubscribe()
  338. // Process each notification, try to run a call in between each of them.
  339. for i := 0; i < count; i++ {
  340. select {
  341. case val := <-nc:
  342. if val != i {
  343. t.Fatalf("(%d/%d) unexpected value %d", i, count, val)
  344. }
  345. case err := <-sub.Err():
  346. if wantError && err != ErrSubscriptionQueueOverflow {
  347. t.Fatalf("(%d/%d) got error %q, want %q", i, count, err, ErrSubscriptionQueueOverflow)
  348. } else if !wantError {
  349. t.Fatalf("(%d/%d) got unexpected error %q", i, count, err)
  350. }
  351. return
  352. }
  353. var r int
  354. err := client.CallContext(ctx, &r, "nftest_echo", i)
  355. if err != nil {
  356. if !wantError {
  357. t.Fatalf("(%d/%d) call error: %v", i, count, err)
  358. }
  359. return
  360. }
  361. }
  362. if wantError {
  363. t.Fatalf("didn't get expected error")
  364. }
  365. }
  366. doTest(8000, false)
  367. doTest(23000, true)
  368. }
  369. func TestClientHTTP(t *testing.T) {
  370. server := newTestServer()
  371. defer server.Stop()
  372. client, hs := httpTestClient(server, "http", nil)
  373. defer hs.Close()
  374. defer client.Close()
  375. // Launch concurrent requests.
  376. var (
  377. results = make([]echoResult, 100)
  378. errc = make(chan error, len(results))
  379. wantResult = echoResult{"a", 1, new(echoArgs)}
  380. )
  381. defer client.Close()
  382. for i := range results {
  383. i := i
  384. go func() {
  385. errc <- client.Call(&results[i], "test_echo", wantResult.String, wantResult.Int, wantResult.Args)
  386. }()
  387. }
  388. // Wait for all of them to complete.
  389. timeout := time.NewTimer(5 * time.Second)
  390. defer timeout.Stop()
  391. for i := range results {
  392. select {
  393. case err := <-errc:
  394. if err != nil {
  395. t.Fatal(err)
  396. }
  397. case <-timeout.C:
  398. t.Fatalf("timeout (got %d/%d) results)", i+1, len(results))
  399. }
  400. }
  401. // Check results.
  402. for i := range results {
  403. if !reflect.DeepEqual(results[i], wantResult) {
  404. t.Errorf("result %d mismatch: got %#v, want %#v", i, results[i], wantResult)
  405. }
  406. }
  407. }
  408. func TestClientReconnect(t *testing.T) {
  409. startServer := func(addr string) (*Server, net.Listener) {
  410. srv := newTestServer()
  411. l, err := net.Listen("tcp", addr)
  412. if err != nil {
  413. t.Fatal("can't listen:", err)
  414. }
  415. go http.Serve(l, srv.WebsocketHandler([]string{"*"}))
  416. return srv, l
  417. }
  418. ctx, cancel := context.WithTimeout(context.Background(), 12*time.Second)
  419. defer cancel()
  420. // Start a server and corresponding client.
  421. s1, l1 := startServer("127.0.0.1:0")
  422. client, err := DialContext(ctx, "ws://"+l1.Addr().String())
  423. if err != nil {
  424. t.Fatal("can't dial", err)
  425. }
  426. // Perform a call. This should work because the server is up.
  427. var resp echoResult
  428. if err := client.CallContext(ctx, &resp, "test_echo", "", 1, nil); err != nil {
  429. t.Fatal(err)
  430. }
  431. // Shut down the server and allow for some cool down time so we can listen on the same
  432. // address again.
  433. l1.Close()
  434. s1.Stop()
  435. time.Sleep(2 * time.Second)
  436. // Try calling again. It shouldn't work.
  437. if err := client.CallContext(ctx, &resp, "test_echo", "", 2, nil); err == nil {
  438. t.Error("successful call while the server is down")
  439. t.Logf("resp: %#v", resp)
  440. }
  441. // Start it up again and call again. The connection should be reestablished.
  442. // We spawn multiple calls here to check whether this hangs somehow.
  443. s2, l2 := startServer(l1.Addr().String())
  444. defer l2.Close()
  445. defer s2.Stop()
  446. start := make(chan struct{})
  447. errors := make(chan error, 20)
  448. for i := 0; i < cap(errors); i++ {
  449. go func() {
  450. <-start
  451. var resp echoResult
  452. errors <- client.CallContext(ctx, &resp, "test_echo", "", 3, nil)
  453. }()
  454. }
  455. close(start)
  456. errcount := 0
  457. for i := 0; i < cap(errors); i++ {
  458. if err = <-errors; err != nil {
  459. errcount++
  460. }
  461. }
  462. t.Logf("%d errors, last error: %v", errcount, err)
  463. if errcount > 1 {
  464. t.Errorf("expected one error after disconnect, got %d", errcount)
  465. }
  466. }
  467. func httpTestClient(srv *Server, transport string, fl *flakeyListener) (*Client, *httptest.Server) {
  468. // Create the HTTP server.
  469. var hs *httptest.Server
  470. switch transport {
  471. case "ws":
  472. hs = httptest.NewUnstartedServer(srv.WebsocketHandler([]string{"*"}))
  473. case "http":
  474. hs = httptest.NewUnstartedServer(srv)
  475. default:
  476. panic("unknown HTTP transport: " + transport)
  477. }
  478. // Wrap the listener if required.
  479. if fl != nil {
  480. fl.Listener = hs.Listener
  481. hs.Listener = fl
  482. }
  483. // Connect the client.
  484. hs.Start()
  485. client, err := Dial(transport + "://" + hs.Listener.Addr().String())
  486. if err != nil {
  487. panic(err)
  488. }
  489. return client, hs
  490. }
  491. func ipcTestClient(srv *Server, fl *flakeyListener) (*Client, net.Listener) {
  492. // Listen on a random endpoint.
  493. endpoint := fmt.Sprintf("go-ethereum-test-ipc-%d-%d", os.Getpid(), rand.Int63())
  494. if runtime.GOOS == "windows" {
  495. endpoint = `\\.\pipe\` + endpoint
  496. } else {
  497. endpoint = os.TempDir() + "/" + endpoint
  498. }
  499. l, err := ipcListen(endpoint)
  500. if err != nil {
  501. panic(err)
  502. }
  503. // Connect the listener to the server.
  504. if fl != nil {
  505. fl.Listener = l
  506. l = fl
  507. }
  508. go srv.ServeListener(l)
  509. // Connect the client.
  510. client, err := Dial(endpoint)
  511. if err != nil {
  512. panic(err)
  513. }
  514. return client, l
  515. }
  516. // flakeyListener kills accepted connections after a random timeout.
  517. type flakeyListener struct {
  518. net.Listener
  519. maxKillTimeout time.Duration
  520. maxAcceptDelay time.Duration
  521. }
  522. func (l *flakeyListener) Accept() (net.Conn, error) {
  523. delay := time.Duration(rand.Int63n(int64(l.maxAcceptDelay)))
  524. time.Sleep(delay)
  525. c, err := l.Listener.Accept()
  526. if err == nil {
  527. timeout := time.Duration(rand.Int63n(int64(l.maxKillTimeout)))
  528. time.AfterFunc(timeout, func() {
  529. log.Debug(fmt.Sprintf("killing conn %v after %v", c.LocalAddr(), timeout))
  530. c.Close()
  531. })
  532. }
  533. return c, err
  534. }