keepalive_test.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725
  1. /*
  2. *
  3. * Copyright 2019 gRPC authors.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. *
  17. */
  18. // This file contains tests related to the following proposals:
  19. // https://github.com/grpc/proposal/blob/master/A8-client-side-keepalive.md
  20. // https://github.com/grpc/proposal/blob/master/A9-server-side-conn-mgt.md
  21. // https://github.com/grpc/proposal/blob/master/A18-tcp-user-timeout.md
  22. package transport
  23. import (
  24. "context"
  25. "fmt"
  26. "io"
  27. "net"
  28. "strings"
  29. "testing"
  30. "time"
  31. "golang.org/x/net/http2"
  32. "google.golang.org/grpc/internal/channelz"
  33. "google.golang.org/grpc/internal/grpctest"
  34. "google.golang.org/grpc/internal/syscall"
  35. "google.golang.org/grpc/keepalive"
  36. )
  37. const defaultTestTimeout = 10 * time.Second
  38. // TestMaxConnectionIdle tests that a server will send GoAway to an idle
  39. // client. An idle client is one who doesn't make any RPC calls for a duration
  40. // of MaxConnectionIdle time.
  41. func (s) TestMaxConnectionIdle(t *testing.T) {
  42. serverConfig := &ServerConfig{
  43. KeepaliveParams: keepalive.ServerParameters{
  44. MaxConnectionIdle: 30 * time.Millisecond,
  45. },
  46. }
  47. server, client, cancel := setUpWithOptions(t, 0, serverConfig, suspended, ConnectOptions{})
  48. defer func() {
  49. client.Close(fmt.Errorf("closed manually by test"))
  50. server.stop()
  51. cancel()
  52. }()
  53. ctx, cancel := context.WithTimeout(context.Background(), defaultTestTimeout)
  54. defer cancel()
  55. stream, err := client.NewStream(ctx, &CallHdr{})
  56. if err != nil {
  57. t.Fatalf("client.NewStream() failed: %v", err)
  58. }
  59. client.CloseStream(stream, io.EOF)
  60. // Verify the server sends a GoAway to client after MaxConnectionIdle timeout
  61. // kicks in.
  62. select {
  63. case <-ctx.Done():
  64. t.Fatalf("context expired before receiving GoAway from the server.")
  65. case <-client.GoAway():
  66. reason, debugMsg := client.GetGoAwayReason()
  67. if reason != GoAwayNoReason {
  68. t.Fatalf("GoAwayReason is %v, want %v", reason, GoAwayNoReason)
  69. }
  70. if !strings.Contains(debugMsg, "max_idle") {
  71. t.Fatalf("GoAwayDebugMessage is %v, want %v", debugMsg, "max_idle")
  72. }
  73. }
  74. }
  75. // TestMaxConnectionIdleBusyClient tests that a server will not send GoAway to
  76. // a busy client.
  77. func (s) TestMaxConnectionIdleBusyClient(t *testing.T) {
  78. serverConfig := &ServerConfig{
  79. KeepaliveParams: keepalive.ServerParameters{
  80. MaxConnectionIdle: 100 * time.Millisecond,
  81. },
  82. }
  83. server, client, cancel := setUpWithOptions(t, 0, serverConfig, suspended, ConnectOptions{})
  84. defer func() {
  85. client.Close(fmt.Errorf("closed manually by test"))
  86. server.stop()
  87. cancel()
  88. }()
  89. ctx, cancel := context.WithTimeout(context.Background(), defaultTestTimeout)
  90. defer cancel()
  91. _, err := client.NewStream(ctx, &CallHdr{})
  92. if err != nil {
  93. t.Fatalf("client.NewStream() failed: %v", err)
  94. }
  95. // Verify the server does not send a GoAway to client even after MaxConnectionIdle
  96. // timeout kicks in.
  97. ctx, cancel = context.WithTimeout(context.Background(), time.Second)
  98. defer cancel()
  99. select {
  100. case <-client.GoAway():
  101. t.Fatalf("A busy client received a GoAway.")
  102. case <-ctx.Done():
  103. }
  104. }
  105. // TestMaxConnectionAge tests that a server will send GoAway after a duration
  106. // of MaxConnectionAge.
  107. func (s) TestMaxConnectionAge(t *testing.T) {
  108. maxConnAge := 100 * time.Millisecond
  109. serverConfig := &ServerConfig{
  110. KeepaliveParams: keepalive.ServerParameters{
  111. MaxConnectionAge: maxConnAge,
  112. MaxConnectionAgeGrace: 10 * time.Millisecond,
  113. },
  114. }
  115. server, client, cancel := setUpWithOptions(t, 0, serverConfig, suspended, ConnectOptions{})
  116. defer func() {
  117. client.Close(fmt.Errorf("closed manually by test"))
  118. server.stop()
  119. cancel()
  120. }()
  121. ctx, cancel := context.WithTimeout(context.Background(), defaultTestTimeout)
  122. defer cancel()
  123. if _, err := client.NewStream(ctx, &CallHdr{}); err != nil {
  124. t.Fatalf("client.NewStream() failed: %v", err)
  125. }
  126. // Verify the server sends a GoAway to client even after client remains idle
  127. // for more than MaxConnectionIdle time.
  128. select {
  129. case <-client.GoAway():
  130. reason, debugMsg := client.GetGoAwayReason()
  131. if reason != GoAwayNoReason {
  132. t.Fatalf("GoAwayReason is %v, want %v", reason, GoAwayNoReason)
  133. }
  134. if !strings.Contains(debugMsg, "max_age") {
  135. t.Fatalf("GoAwayDebugMessage is %v, want %v", debugMsg, "max_age")
  136. }
  137. case <-ctx.Done():
  138. t.Fatalf("timed out before getting a GoAway from the server.")
  139. }
  140. }
  141. const (
  142. defaultWriteBufSize = 32 * 1024
  143. defaultReadBufSize = 32 * 1024
  144. )
  145. // TestKeepaliveServerClosesUnresponsiveClient tests that a server closes
  146. // the connection with a client that doesn't respond to keepalive pings.
  147. //
  148. // This test creates a regular net.Conn connection to the server and sends the
  149. // clientPreface and the initial Settings frame, and then remains unresponsive.
  150. func (s) TestKeepaliveServerClosesUnresponsiveClient(t *testing.T) {
  151. serverConfig := &ServerConfig{
  152. KeepaliveParams: keepalive.ServerParameters{
  153. Time: 100 * time.Millisecond,
  154. Timeout: 10 * time.Millisecond,
  155. },
  156. }
  157. server, client, cancel := setUpWithOptions(t, 0, serverConfig, suspended, ConnectOptions{})
  158. defer func() {
  159. client.Close(fmt.Errorf("closed manually by test"))
  160. server.stop()
  161. cancel()
  162. }()
  163. addr := server.addr()
  164. conn, err := net.Dial("tcp", addr)
  165. if err != nil {
  166. t.Fatalf("net.Dial(tcp, %v) failed: %v", addr, err)
  167. }
  168. defer conn.Close()
  169. if n, err := conn.Write(clientPreface); err != nil || n != len(clientPreface) {
  170. t.Fatalf("conn.Write(clientPreface) failed: n=%v, err=%v", n, err)
  171. }
  172. framer := newFramer(conn, defaultWriteBufSize, defaultReadBufSize, 0)
  173. if err := framer.fr.WriteSettings(http2.Setting{}); err != nil {
  174. t.Fatal("framer.WriteSettings(http2.Setting{}) failed:", err)
  175. }
  176. framer.writer.Flush()
  177. // We read from the net.Conn till we get an error, which is expected when
  178. // the server closes the connection as part of the keepalive logic.
  179. errCh := make(chan error, 1)
  180. go func() {
  181. b := make([]byte, 24)
  182. for {
  183. if _, err = conn.Read(b); err != nil {
  184. errCh <- err
  185. return
  186. }
  187. }
  188. }()
  189. // Server waits for KeepaliveParams.Time seconds before sending out a ping,
  190. // and then waits for KeepaliveParams.Timeout for a ping ack.
  191. ctx, cancel := context.WithTimeout(context.Background(), defaultTestTimeout)
  192. defer cancel()
  193. select {
  194. case err := <-errCh:
  195. if err != io.EOF {
  196. t.Fatalf("client.Read(_) = _,%v, want io.EOF", err)
  197. }
  198. case <-ctx.Done():
  199. t.Fatalf("Test timed out before server closed the connection.")
  200. }
  201. }
  202. // TestKeepaliveServerWithResponsiveClient tests that a server doesn't close
  203. // the connection with a client that responds to keepalive pings.
  204. func (s) TestKeepaliveServerWithResponsiveClient(t *testing.T) {
  205. serverConfig := &ServerConfig{
  206. KeepaliveParams: keepalive.ServerParameters{
  207. Time: 100 * time.Millisecond,
  208. Timeout: 100 * time.Millisecond,
  209. },
  210. }
  211. server, client, cancel := setUpWithOptions(t, 0, serverConfig, suspended, ConnectOptions{})
  212. defer func() {
  213. client.Close(fmt.Errorf("closed manually by test"))
  214. server.stop()
  215. cancel()
  216. }()
  217. // Give keepalive logic some time by sleeping.
  218. time.Sleep(500 * time.Millisecond)
  219. if err := checkForHealthyStream(client); err != nil {
  220. t.Fatalf("Stream creation failed: %v", err)
  221. }
  222. }
  223. // TestKeepaliveClientClosesUnresponsiveServer creates a server which does not
  224. // respond to keepalive pings, and makes sure that the client closes the
  225. // transport once the keepalive logic kicks in. Here, we set the
  226. // `PermitWithoutStream` parameter to true which ensures that the keepalive
  227. // logic is running even without any active streams.
  228. func (s) TestKeepaliveClientClosesUnresponsiveServer(t *testing.T) {
  229. connCh := make(chan net.Conn, 1)
  230. copts := ConnectOptions{
  231. ChannelzParentID: channelz.NewIdentifierForTesting(channelz.RefSubChannel, time.Now().Unix(), nil),
  232. KeepaliveParams: keepalive.ClientParameters{
  233. Time: 10 * time.Millisecond,
  234. Timeout: 10 * time.Millisecond,
  235. PermitWithoutStream: true,
  236. },
  237. }
  238. client, cancel := setUpWithNoPingServer(t, copts, connCh)
  239. defer cancel()
  240. defer client.Close(fmt.Errorf("closed manually by test"))
  241. conn, ok := <-connCh
  242. if !ok {
  243. t.Fatalf("Server didn't return connection object")
  244. }
  245. defer conn.Close()
  246. if err := pollForStreamCreationError(client); err != nil {
  247. t.Fatal(err)
  248. }
  249. }
  250. // TestKeepaliveClientOpenWithUnresponsiveServer creates a server which does
  251. // not respond to keepalive pings, and makes sure that the client does not
  252. // close the transport. Here, we do not set the `PermitWithoutStream` parameter
  253. // to true which ensures that the keepalive logic is turned off without any
  254. // active streams, and therefore the transport stays open.
  255. func (s) TestKeepaliveClientOpenWithUnresponsiveServer(t *testing.T) {
  256. connCh := make(chan net.Conn, 1)
  257. copts := ConnectOptions{
  258. ChannelzParentID: channelz.NewIdentifierForTesting(channelz.RefSubChannel, time.Now().Unix(), nil),
  259. KeepaliveParams: keepalive.ClientParameters{
  260. Time: 10 * time.Millisecond,
  261. Timeout: 10 * time.Millisecond,
  262. },
  263. }
  264. client, cancel := setUpWithNoPingServer(t, copts, connCh)
  265. defer cancel()
  266. defer client.Close(fmt.Errorf("closed manually by test"))
  267. conn, ok := <-connCh
  268. if !ok {
  269. t.Fatalf("Server didn't return connection object")
  270. }
  271. defer conn.Close()
  272. // Give keepalive some time.
  273. time.Sleep(500 * time.Millisecond)
  274. if err := checkForHealthyStream(client); err != nil {
  275. t.Fatalf("Stream creation failed: %v", err)
  276. }
  277. }
  278. // TestKeepaliveClientClosesWithActiveStreams creates a server which does not
  279. // respond to keepalive pings, and makes sure that the client closes the
  280. // transport even when there is an active stream.
  281. func (s) TestKeepaliveClientClosesWithActiveStreams(t *testing.T) {
  282. connCh := make(chan net.Conn, 1)
  283. copts := ConnectOptions{
  284. ChannelzParentID: channelz.NewIdentifierForTesting(channelz.RefSubChannel, time.Now().Unix(), nil),
  285. KeepaliveParams: keepalive.ClientParameters{
  286. Time: 500 * time.Millisecond,
  287. Timeout: 500 * time.Millisecond,
  288. },
  289. }
  290. // TODO(i/6099): Setup a server which can ping and no-ping based on a flag to
  291. // reduce the flakiness in this test.
  292. client, cancel := setUpWithNoPingServer(t, copts, connCh)
  293. defer cancel()
  294. defer client.Close(fmt.Errorf("closed manually by test"))
  295. conn, ok := <-connCh
  296. if !ok {
  297. t.Fatalf("Server didn't return connection object")
  298. }
  299. defer conn.Close()
  300. ctx, cancel := context.WithTimeout(context.Background(), defaultTestTimeout)
  301. defer cancel()
  302. // Create a stream, but send no data on it.
  303. if _, err := client.NewStream(ctx, &CallHdr{}); err != nil {
  304. t.Fatalf("Stream creation failed: %v", err)
  305. }
  306. if err := pollForStreamCreationError(client); err != nil {
  307. t.Fatal(err)
  308. }
  309. }
  310. // TestKeepaliveClientStaysHealthyWithResponsiveServer creates a server which
  311. // responds to keepalive pings, and makes sure than a client transport stays
  312. // healthy without any active streams.
  313. func (s) TestKeepaliveClientStaysHealthyWithResponsiveServer(t *testing.T) {
  314. server, client, cancel := setUpWithOptions(t, 0,
  315. &ServerConfig{
  316. KeepalivePolicy: keepalive.EnforcementPolicy{
  317. MinTime: 50 * time.Millisecond,
  318. PermitWithoutStream: true,
  319. },
  320. },
  321. normal,
  322. ConnectOptions{
  323. KeepaliveParams: keepalive.ClientParameters{
  324. Time: 55 * time.Millisecond,
  325. Timeout: time.Second,
  326. PermitWithoutStream: true,
  327. }})
  328. defer func() {
  329. client.Close(fmt.Errorf("closed manually by test"))
  330. server.stop()
  331. cancel()
  332. }()
  333. // Give keepalive some time.
  334. time.Sleep(500 * time.Millisecond)
  335. if err := checkForHealthyStream(client); err != nil {
  336. t.Fatalf("Stream creation failed: %v", err)
  337. }
  338. }
  339. // TestKeepaliveClientFrequency creates a server which expects at most 1 client
  340. // ping for every 100 ms, while the client is configured to send a ping
  341. // every 50 ms. So, this configuration should end up with the client
  342. // transport being closed. But we had a bug wherein the client was sending one
  343. // ping every [Time+Timeout] instead of every [Time] period, and this test
  344. // explicitly makes sure the fix works and the client sends a ping every [Time]
  345. // period.
  346. func (s) TestKeepaliveClientFrequency(t *testing.T) {
  347. grpctest.TLogger.ExpectError("Client received GoAway with error code ENHANCE_YOUR_CALM and debug data equal to ASCII \"too_many_pings\"")
  348. serverConfig := &ServerConfig{
  349. KeepalivePolicy: keepalive.EnforcementPolicy{
  350. MinTime: 100 * time.Millisecond,
  351. PermitWithoutStream: true,
  352. },
  353. }
  354. clientOptions := ConnectOptions{
  355. KeepaliveParams: keepalive.ClientParameters{
  356. Time: 50 * time.Millisecond,
  357. Timeout: time.Second,
  358. PermitWithoutStream: true,
  359. },
  360. }
  361. server, client, cancel := setUpWithOptions(t, 0, serverConfig, normal, clientOptions)
  362. defer func() {
  363. client.Close(fmt.Errorf("closed manually by test"))
  364. server.stop()
  365. cancel()
  366. }()
  367. if err := waitForGoAwayTooManyPings(client); err != nil {
  368. t.Fatal(err)
  369. }
  370. }
  371. // TestKeepaliveServerEnforcementWithAbusiveClientNoRPC verifies that the
  372. // server closes a client transport when it sends too many keepalive pings
  373. // (when there are no active streams), based on the configured
  374. // EnforcementPolicy.
  375. func (s) TestKeepaliveServerEnforcementWithAbusiveClientNoRPC(t *testing.T) {
  376. grpctest.TLogger.ExpectError("Client received GoAway with error code ENHANCE_YOUR_CALM and debug data equal to ASCII \"too_many_pings\"")
  377. serverConfig := &ServerConfig{
  378. KeepalivePolicy: keepalive.EnforcementPolicy{
  379. MinTime: time.Second,
  380. },
  381. }
  382. clientOptions := ConnectOptions{
  383. KeepaliveParams: keepalive.ClientParameters{
  384. Time: 20 * time.Millisecond,
  385. Timeout: 100 * time.Millisecond,
  386. PermitWithoutStream: true,
  387. },
  388. }
  389. server, client, cancel := setUpWithOptions(t, 0, serverConfig, normal, clientOptions)
  390. defer func() {
  391. client.Close(fmt.Errorf("closed manually by test"))
  392. server.stop()
  393. cancel()
  394. }()
  395. if err := waitForGoAwayTooManyPings(client); err != nil {
  396. t.Fatal(err)
  397. }
  398. }
  399. // TestKeepaliveServerEnforcementWithAbusiveClientWithRPC verifies that the
  400. // server closes a client transport when it sends too many keepalive pings
  401. // (even when there is an active stream), based on the configured
  402. // EnforcementPolicy.
  403. func (s) TestKeepaliveServerEnforcementWithAbusiveClientWithRPC(t *testing.T) {
  404. grpctest.TLogger.ExpectError("Client received GoAway with error code ENHANCE_YOUR_CALM and debug data equal to ASCII \"too_many_pings\"")
  405. serverConfig := &ServerConfig{
  406. KeepalivePolicy: keepalive.EnforcementPolicy{
  407. MinTime: time.Second,
  408. },
  409. }
  410. clientOptions := ConnectOptions{
  411. KeepaliveParams: keepalive.ClientParameters{
  412. Time: 50 * time.Millisecond,
  413. Timeout: 100 * time.Millisecond,
  414. },
  415. }
  416. server, client, cancel := setUpWithOptions(t, 0, serverConfig, suspended, clientOptions)
  417. defer func() {
  418. client.Close(fmt.Errorf("closed manually by test"))
  419. server.stop()
  420. cancel()
  421. }()
  422. ctx, cancel := context.WithTimeout(context.Background(), defaultTestTimeout)
  423. defer cancel()
  424. if _, err := client.NewStream(ctx, &CallHdr{}); err != nil {
  425. t.Fatalf("Stream creation failed: %v", err)
  426. }
  427. if err := waitForGoAwayTooManyPings(client); err != nil {
  428. t.Fatal(err)
  429. }
  430. }
  431. // TestKeepaliveServerEnforcementWithObeyingClientNoRPC verifies that the
  432. // server does not close a client transport (with no active streams) which
  433. // sends keepalive pings in accordance to the configured keepalive
  434. // EnforcementPolicy.
  435. func (s) TestKeepaliveServerEnforcementWithObeyingClientNoRPC(t *testing.T) {
  436. serverConfig := &ServerConfig{
  437. KeepalivePolicy: keepalive.EnforcementPolicy{
  438. MinTime: 40 * time.Millisecond,
  439. PermitWithoutStream: true,
  440. },
  441. }
  442. clientOptions := ConnectOptions{
  443. KeepaliveParams: keepalive.ClientParameters{
  444. Time: 50 * time.Millisecond,
  445. Timeout: time.Second,
  446. PermitWithoutStream: true,
  447. },
  448. }
  449. server, client, cancel := setUpWithOptions(t, 0, serverConfig, normal, clientOptions)
  450. defer func() {
  451. client.Close(fmt.Errorf("closed manually by test"))
  452. server.stop()
  453. cancel()
  454. }()
  455. // Sleep for client to send ~10 keepalive pings.
  456. time.Sleep(500 * time.Millisecond)
  457. // Verify that the server does not close the client transport.
  458. if err := checkForHealthyStream(client); err != nil {
  459. t.Fatalf("Stream creation failed: %v", err)
  460. }
  461. }
  462. // TestKeepaliveServerEnforcementWithObeyingClientWithRPC verifies that the
  463. // server does not close a client transport (with active streams) which
  464. // sends keepalive pings in accordance to the configured keepalive
  465. // EnforcementPolicy.
  466. func (s) TestKeepaliveServerEnforcementWithObeyingClientWithRPC(t *testing.T) {
  467. serverConfig := &ServerConfig{
  468. KeepalivePolicy: keepalive.EnforcementPolicy{
  469. MinTime: 40 * time.Millisecond,
  470. },
  471. }
  472. clientOptions := ConnectOptions{
  473. KeepaliveParams: keepalive.ClientParameters{
  474. Time: 50 * time.Millisecond,
  475. },
  476. }
  477. server, client, cancel := setUpWithOptions(t, 0, serverConfig, suspended, clientOptions)
  478. defer func() {
  479. client.Close(fmt.Errorf("closed manually by test"))
  480. server.stop()
  481. cancel()
  482. }()
  483. if err := checkForHealthyStream(client); err != nil {
  484. t.Fatalf("Stream creation failed: %v", err)
  485. }
  486. // Give keepalive enough time.
  487. time.Sleep(500 * time.Millisecond)
  488. if err := checkForHealthyStream(client); err != nil {
  489. t.Fatalf("Stream creation failed: %v", err)
  490. }
  491. }
  492. // TestKeepaliveServerEnforcementWithDormantKeepaliveOnClient verifies that the
  493. // server does not closes a client transport, which has been configured to send
  494. // more pings than allowed by the server's EnforcementPolicy. This client
  495. // transport does not have any active streams and `PermitWithoutStream` is set
  496. // to false. This should ensure that the keepalive functionality on the client
  497. // side enters a dormant state.
  498. func (s) TestKeepaliveServerEnforcementWithDormantKeepaliveOnClient(t *testing.T) {
  499. serverConfig := &ServerConfig{
  500. KeepalivePolicy: keepalive.EnforcementPolicy{
  501. MinTime: 100 * time.Millisecond,
  502. },
  503. }
  504. clientOptions := ConnectOptions{
  505. KeepaliveParams: keepalive.ClientParameters{
  506. Time: 10 * time.Millisecond,
  507. Timeout: 10 * time.Millisecond,
  508. },
  509. }
  510. server, client, cancel := setUpWithOptions(t, 0, serverConfig, normal, clientOptions)
  511. defer func() {
  512. client.Close(fmt.Errorf("closed manually by test"))
  513. server.stop()
  514. cancel()
  515. }()
  516. // No active streams on the client. Give keepalive enough time.
  517. time.Sleep(500 * time.Millisecond)
  518. if err := checkForHealthyStream(client); err != nil {
  519. t.Fatalf("Stream creation failed: %v", err)
  520. }
  521. }
  522. // TestTCPUserTimeout tests that the TCP_USER_TIMEOUT socket option is set to
  523. // the keepalive timeout, as detailed in proposal A18.
  524. func (s) TestTCPUserTimeout(t *testing.T) {
  525. tests := []struct {
  526. time time.Duration
  527. timeout time.Duration
  528. clientWantTimeout time.Duration
  529. serverWantTimeout time.Duration
  530. }{
  531. {
  532. 10 * time.Second,
  533. 10 * time.Second,
  534. 10 * 1000 * time.Millisecond,
  535. 10 * 1000 * time.Millisecond,
  536. },
  537. {
  538. 0,
  539. 0,
  540. 0,
  541. 20 * 1000 * time.Millisecond,
  542. },
  543. {
  544. infinity,
  545. infinity,
  546. 0,
  547. 0,
  548. },
  549. }
  550. for _, tt := range tests {
  551. server, client, cancel := setUpWithOptions(
  552. t,
  553. 0,
  554. &ServerConfig{
  555. KeepaliveParams: keepalive.ServerParameters{
  556. Time: tt.time,
  557. Timeout: tt.timeout,
  558. },
  559. },
  560. normal,
  561. ConnectOptions{
  562. KeepaliveParams: keepalive.ClientParameters{
  563. Time: tt.time,
  564. Timeout: tt.timeout,
  565. },
  566. },
  567. )
  568. defer func() {
  569. client.Close(fmt.Errorf("closed manually by test"))
  570. server.stop()
  571. cancel()
  572. }()
  573. var sc *http2Server
  574. // Wait until the server transport is setup.
  575. for {
  576. server.mu.Lock()
  577. if len(server.conns) == 0 {
  578. server.mu.Unlock()
  579. time.Sleep(time.Millisecond)
  580. continue
  581. }
  582. for k := range server.conns {
  583. var ok bool
  584. sc, ok = k.(*http2Server)
  585. if !ok {
  586. t.Fatalf("Failed to convert %v to *http2Server", k)
  587. }
  588. }
  589. server.mu.Unlock()
  590. break
  591. }
  592. ctx, cancel := context.WithTimeout(context.Background(), defaultTestTimeout)
  593. defer cancel()
  594. stream, err := client.NewStream(ctx, &CallHdr{})
  595. if err != nil {
  596. t.Fatalf("client.NewStream() failed: %v", err)
  597. }
  598. client.CloseStream(stream, io.EOF)
  599. cltOpt, err := syscall.GetTCPUserTimeout(client.conn)
  600. if err != nil {
  601. t.Fatalf("syscall.GetTCPUserTimeout() failed: %v", err)
  602. }
  603. if cltOpt < 0 {
  604. t.Skipf("skipping test on unsupported environment")
  605. }
  606. if gotTimeout := time.Duration(cltOpt) * time.Millisecond; gotTimeout != tt.clientWantTimeout {
  607. t.Fatalf("syscall.GetTCPUserTimeout() = %d, want %d", gotTimeout, tt.clientWantTimeout)
  608. }
  609. srvOpt, err := syscall.GetTCPUserTimeout(sc.conn)
  610. if err != nil {
  611. t.Fatalf("syscall.GetTCPUserTimeout() failed: %v", err)
  612. }
  613. if gotTimeout := time.Duration(srvOpt) * time.Millisecond; gotTimeout != tt.serverWantTimeout {
  614. t.Fatalf("syscall.GetTCPUserTimeout() = %d, want %d", gotTimeout, tt.serverWantTimeout)
  615. }
  616. }
  617. }
  618. // checkForHealthyStream attempts to create a stream and return error if any.
  619. // The stream created is closed right after to avoid any leakages.
  620. func checkForHealthyStream(client *http2Client) error {
  621. ctx, cancel := context.WithTimeout(context.Background(), defaultTestTimeout)
  622. defer cancel()
  623. stream, err := client.NewStream(ctx, &CallHdr{})
  624. client.CloseStream(stream, err)
  625. return err
  626. }
  627. func pollForStreamCreationError(client *http2Client) error {
  628. ctx, cancel := context.WithTimeout(context.Background(), defaultTestTimeout)
  629. defer cancel()
  630. for {
  631. if _, err := client.NewStream(ctx, &CallHdr{}); err != nil {
  632. break
  633. }
  634. time.Sleep(50 * time.Millisecond)
  635. }
  636. if ctx.Err() != nil {
  637. return fmt.Errorf("test timed out before stream creation returned an error")
  638. }
  639. return nil
  640. }
  641. // waitForGoAwayTooManyPings waits for client to receive a GoAwayTooManyPings
  642. // from server. It also asserts that stream creation fails after receiving a
  643. // GoAway.
  644. func waitForGoAwayTooManyPings(client *http2Client) error {
  645. ctx, cancel := context.WithTimeout(context.Background(), defaultTestTimeout)
  646. defer cancel()
  647. select {
  648. case <-client.GoAway():
  649. if reason, _ := client.GetGoAwayReason(); reason != GoAwayTooManyPings {
  650. return fmt.Errorf("goAwayReason is %v, want %v", reason, GoAwayTooManyPings)
  651. }
  652. case <-ctx.Done():
  653. return fmt.Errorf("test timed out before getting GoAway with reason:GoAwayTooManyPings from server")
  654. }
  655. if _, err := client.NewStream(ctx, &CallHdr{}); err == nil {
  656. return fmt.Errorf("stream creation succeeded after receiving a GoAway from the server")
  657. }
  658. return nil
  659. }