client_test.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586
  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 = 6
  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. sleepTime := maxContextCancelTimeout + 20*time.Millisecond
  189. err := client.CallContext(ctx, nil, "test_sleep", sleepTime)
  190. if err != nil {
  191. log.Debug(fmt.Sprint("got expected error:", err))
  192. } else {
  193. t.Errorf("no error for call with %v wait time", timeout)
  194. }
  195. cancel()
  196. }
  197. }
  198. wg.Add(ncallers)
  199. for i := 0; i < ncallers; i++ {
  200. go caller(i)
  201. }
  202. wg.Wait()
  203. }
  204. func TestClientSubscribeInvalidArg(t *testing.T) {
  205. server := newTestServer()
  206. defer server.Stop()
  207. client := DialInProc(server)
  208. defer client.Close()
  209. check := func(shouldPanic bool, arg interface{}) {
  210. defer func() {
  211. err := recover()
  212. if shouldPanic && err == nil {
  213. t.Errorf("EthSubscribe should've panicked for %#v", arg)
  214. }
  215. if !shouldPanic && err != nil {
  216. t.Errorf("EthSubscribe shouldn't have panicked for %#v", arg)
  217. buf := make([]byte, 1024*1024)
  218. buf = buf[:runtime.Stack(buf, false)]
  219. t.Error(err)
  220. t.Error(string(buf))
  221. }
  222. }()
  223. client.EthSubscribe(context.Background(), arg, "foo_bar")
  224. }
  225. check(true, nil)
  226. check(true, 1)
  227. check(true, (chan int)(nil))
  228. check(true, make(<-chan int))
  229. check(false, make(chan int))
  230. check(false, make(chan<- int))
  231. }
  232. func TestClientSubscribe(t *testing.T) {
  233. server := newTestServer()
  234. defer server.Stop()
  235. client := DialInProc(server)
  236. defer client.Close()
  237. nc := make(chan int)
  238. count := 10
  239. sub, err := client.Subscribe(context.Background(), "nftest", nc, "someSubscription", count, 0)
  240. if err != nil {
  241. t.Fatal("can't subscribe:", err)
  242. }
  243. for i := 0; i < count; i++ {
  244. if val := <-nc; val != i {
  245. t.Fatalf("value mismatch: got %d, want %d", val, i)
  246. }
  247. }
  248. sub.Unsubscribe()
  249. select {
  250. case v := <-nc:
  251. t.Fatal("received value after unsubscribe:", v)
  252. case err := <-sub.Err():
  253. if err != nil {
  254. t.Fatalf("Err returned a non-nil error after explicit unsubscribe: %q", err)
  255. }
  256. case <-time.After(1 * time.Second):
  257. t.Fatalf("subscription not closed within 1s after unsubscribe")
  258. }
  259. }
  260. // In this test, the connection drops while Subscribe is waiting for a response.
  261. func TestClientSubscribeClose(t *testing.T) {
  262. server := newTestServer()
  263. service := &notificationTestService{
  264. gotHangSubscriptionReq: make(chan struct{}),
  265. unblockHangSubscription: make(chan struct{}),
  266. }
  267. if err := server.RegisterName("nftest2", service); err != nil {
  268. t.Fatal(err)
  269. }
  270. defer server.Stop()
  271. client := DialInProc(server)
  272. defer client.Close()
  273. var (
  274. nc = make(chan int)
  275. errc = make(chan error, 1)
  276. sub *ClientSubscription
  277. err error
  278. )
  279. go func() {
  280. sub, err = client.Subscribe(context.Background(), "nftest2", nc, "hangSubscription", 999)
  281. errc <- err
  282. }()
  283. <-service.gotHangSubscriptionReq
  284. client.Close()
  285. service.unblockHangSubscription <- struct{}{}
  286. select {
  287. case err := <-errc:
  288. if err == nil {
  289. t.Errorf("Subscribe returned nil error after Close")
  290. }
  291. if sub != nil {
  292. t.Error("Subscribe returned non-nil subscription after Close")
  293. }
  294. case <-time.After(1 * time.Second):
  295. t.Fatalf("Subscribe did not return within 1s after Close")
  296. }
  297. }
  298. // This test reproduces https://github.com/ethereum/go-ethereum/issues/17837 where the
  299. // client hangs during shutdown when Unsubscribe races with Client.Close.
  300. func TestClientCloseUnsubscribeRace(t *testing.T) {
  301. server := newTestServer()
  302. defer server.Stop()
  303. for i := 0; i < 20; i++ {
  304. client := DialInProc(server)
  305. nc := make(chan int)
  306. sub, err := client.Subscribe(context.Background(), "nftest", nc, "someSubscription", 3, 1)
  307. if err != nil {
  308. t.Fatal(err)
  309. }
  310. go client.Close()
  311. go sub.Unsubscribe()
  312. select {
  313. case <-sub.Err():
  314. case <-time.After(5 * time.Second):
  315. t.Fatal("subscription not closed within timeout")
  316. }
  317. }
  318. }
  319. // This test checks that Client doesn't lock up when a single subscriber
  320. // doesn't read subscription events.
  321. func TestClientNotificationStorm(t *testing.T) {
  322. server := newTestServer()
  323. defer server.Stop()
  324. doTest := func(count int, wantError bool) {
  325. client := DialInProc(server)
  326. defer client.Close()
  327. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  328. defer cancel()
  329. // Subscribe on the server. It will start sending many notifications
  330. // very quickly.
  331. nc := make(chan int)
  332. sub, err := client.Subscribe(ctx, "nftest", nc, "someSubscription", count, 0)
  333. if err != nil {
  334. t.Fatal("can't subscribe:", err)
  335. }
  336. defer sub.Unsubscribe()
  337. // Process each notification, try to run a call in between each of them.
  338. for i := 0; i < count; i++ {
  339. select {
  340. case val := <-nc:
  341. if val != i {
  342. t.Fatalf("(%d/%d) unexpected value %d", i, count, val)
  343. }
  344. case err := <-sub.Err():
  345. if wantError && err != ErrSubscriptionQueueOverflow {
  346. t.Fatalf("(%d/%d) got error %q, want %q", i, count, err, ErrSubscriptionQueueOverflow)
  347. } else if !wantError {
  348. t.Fatalf("(%d/%d) got unexpected error %q", i, count, err)
  349. }
  350. return
  351. }
  352. var r int
  353. err := client.CallContext(ctx, &r, "nftest_echo", i)
  354. if err != nil {
  355. if !wantError {
  356. t.Fatalf("(%d/%d) call error: %v", i, count, err)
  357. }
  358. return
  359. }
  360. }
  361. if wantError {
  362. t.Fatalf("didn't get expected error")
  363. }
  364. }
  365. doTest(8000, false)
  366. doTest(23000, true)
  367. }
  368. func TestClientHTTP(t *testing.T) {
  369. server := newTestServer()
  370. defer server.Stop()
  371. client, hs := httpTestClient(server, "http", nil)
  372. defer hs.Close()
  373. defer client.Close()
  374. // Launch concurrent requests.
  375. var (
  376. results = make([]echoResult, 100)
  377. errc = make(chan error)
  378. wantResult = echoResult{"a", 1, new(echoArgs)}
  379. )
  380. defer client.Close()
  381. for i := range results {
  382. i := i
  383. go func() {
  384. errc <- client.Call(&results[i], "test_echo",
  385. 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. }