client_test.go 15 KB

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