clientconn_test.go 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364
  1. /*
  2. *
  3. * Copyright 2014 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. package grpc
  19. import (
  20. "context"
  21. "errors"
  22. "fmt"
  23. "math"
  24. "net"
  25. "strings"
  26. "sync/atomic"
  27. "testing"
  28. "time"
  29. "golang.org/x/net/http2"
  30. "google.golang.org/grpc/connectivity"
  31. "google.golang.org/grpc/credentials"
  32. "google.golang.org/grpc/internal/backoff"
  33. "google.golang.org/grpc/internal/envconfig"
  34. "google.golang.org/grpc/internal/transport"
  35. "google.golang.org/grpc/keepalive"
  36. "google.golang.org/grpc/naming"
  37. "google.golang.org/grpc/resolver"
  38. "google.golang.org/grpc/resolver/manual"
  39. _ "google.golang.org/grpc/resolver/passthrough"
  40. "google.golang.org/grpc/testdata"
  41. )
  42. func assertState(wantState connectivity.State, cc *ClientConn) (connectivity.State, bool) {
  43. ctx, cancel := context.WithTimeout(context.Background(), time.Second)
  44. defer cancel()
  45. var state connectivity.State
  46. for state = cc.GetState(); state != wantState && cc.WaitForStateChange(ctx, state); state = cc.GetState() {
  47. }
  48. return state, state == wantState
  49. }
  50. func (s) TestDialWithTimeout(t *testing.T) {
  51. lis, err := net.Listen("tcp", "localhost:0")
  52. if err != nil {
  53. t.Fatalf("Error while listening. Err: %v", err)
  54. }
  55. defer lis.Close()
  56. lisAddr := resolver.Address{Addr: lis.Addr().String()}
  57. lisDone := make(chan struct{})
  58. dialDone := make(chan struct{})
  59. // 1st listener accepts the connection and then does nothing
  60. go func() {
  61. defer close(lisDone)
  62. conn, err := lis.Accept()
  63. if err != nil {
  64. t.Errorf("Error while accepting. Err: %v", err)
  65. return
  66. }
  67. framer := http2.NewFramer(conn, conn)
  68. if err := framer.WriteSettings(http2.Setting{}); err != nil {
  69. t.Errorf("Error while writing settings. Err: %v", err)
  70. return
  71. }
  72. <-dialDone // Close conn only after dial returns.
  73. }()
  74. r, cleanup := manual.GenerateAndRegisterManualResolver()
  75. defer cleanup()
  76. r.InitialState(resolver.State{Addresses: []resolver.Address{lisAddr}})
  77. client, err := Dial(r.Scheme()+":///test.server", WithInsecure(), WithTimeout(5*time.Second))
  78. close(dialDone)
  79. if err != nil {
  80. t.Fatalf("Dial failed. Err: %v", err)
  81. }
  82. defer client.Close()
  83. timeout := time.After(1 * time.Second)
  84. select {
  85. case <-timeout:
  86. t.Fatal("timed out waiting for server to finish")
  87. case <-lisDone:
  88. }
  89. }
  90. func (s) TestDialWithMultipleBackendsNotSendingServerPreface(t *testing.T) {
  91. lis1, err := net.Listen("tcp", "localhost:0")
  92. if err != nil {
  93. t.Fatalf("Error while listening. Err: %v", err)
  94. }
  95. defer lis1.Close()
  96. lis1Addr := resolver.Address{Addr: lis1.Addr().String()}
  97. lis1Done := make(chan struct{})
  98. // 1st listener accepts the connection and immediately closes it.
  99. go func() {
  100. defer close(lis1Done)
  101. conn, err := lis1.Accept()
  102. if err != nil {
  103. t.Errorf("Error while accepting. Err: %v", err)
  104. return
  105. }
  106. conn.Close()
  107. }()
  108. lis2, err := net.Listen("tcp", "localhost:0")
  109. if err != nil {
  110. t.Fatalf("Error while listening. Err: %v", err)
  111. }
  112. defer lis2.Close()
  113. lis2Done := make(chan struct{})
  114. lis2Addr := resolver.Address{Addr: lis2.Addr().String()}
  115. // 2nd listener should get a connection attempt since the first one failed.
  116. go func() {
  117. defer close(lis2Done)
  118. _, err := lis2.Accept() // Closing the client will clean up this conn.
  119. if err != nil {
  120. t.Errorf("Error while accepting. Err: %v", err)
  121. return
  122. }
  123. }()
  124. r, cleanup := manual.GenerateAndRegisterManualResolver()
  125. defer cleanup()
  126. r.InitialState(resolver.State{Addresses: []resolver.Address{lis1Addr, lis2Addr}})
  127. client, err := Dial(r.Scheme()+":///test.server", WithInsecure())
  128. if err != nil {
  129. t.Fatalf("Dial failed. Err: %v", err)
  130. }
  131. defer client.Close()
  132. timeout := time.After(5 * time.Second)
  133. select {
  134. case <-timeout:
  135. t.Fatal("timed out waiting for server 1 to finish")
  136. case <-lis1Done:
  137. }
  138. select {
  139. case <-timeout:
  140. t.Fatal("timed out waiting for server 2 to finish")
  141. case <-lis2Done:
  142. }
  143. }
  144. var allReqHSSettings = []envconfig.RequireHandshakeSetting{
  145. envconfig.RequireHandshakeOff,
  146. envconfig.RequireHandshakeOn,
  147. }
  148. func (s) TestDialWaitsForServerSettings(t *testing.T) {
  149. // Restore current setting after test.
  150. old := envconfig.RequireHandshake
  151. defer func() { envconfig.RequireHandshake = old }()
  152. // Test with all environment variable settings, which should not impact the
  153. // test case since WithWaitForHandshake has higher priority.
  154. for _, setting := range allReqHSSettings {
  155. envconfig.RequireHandshake = setting
  156. lis, err := net.Listen("tcp", "localhost:0")
  157. if err != nil {
  158. t.Fatalf("Error while listening. Err: %v", err)
  159. }
  160. defer lis.Close()
  161. done := make(chan struct{})
  162. sent := make(chan struct{})
  163. dialDone := make(chan struct{})
  164. go func() { // Launch the server.
  165. defer func() {
  166. close(done)
  167. }()
  168. conn, err := lis.Accept()
  169. if err != nil {
  170. t.Errorf("Error while accepting. Err: %v", err)
  171. return
  172. }
  173. defer conn.Close()
  174. // Sleep for a little bit to make sure that Dial on client
  175. // side blocks until settings are received.
  176. time.Sleep(100 * time.Millisecond)
  177. framer := http2.NewFramer(conn, conn)
  178. close(sent)
  179. if err := framer.WriteSettings(http2.Setting{}); err != nil {
  180. t.Errorf("Error while writing settings. Err: %v", err)
  181. return
  182. }
  183. <-dialDone // Close conn only after dial returns.
  184. }()
  185. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  186. defer cancel()
  187. client, err := DialContext(ctx, lis.Addr().String(), WithInsecure(), WithWaitForHandshake(), WithBlock())
  188. close(dialDone)
  189. if err != nil {
  190. t.Fatalf("Error while dialing. Err: %v", err)
  191. }
  192. defer client.Close()
  193. select {
  194. case <-sent:
  195. default:
  196. t.Fatalf("Dial returned before server settings were sent")
  197. }
  198. <-done
  199. }
  200. }
  201. func (s) TestDialWaitsForServerSettingsViaEnv(t *testing.T) {
  202. // Set default behavior and restore current setting after test.
  203. old := envconfig.RequireHandshake
  204. envconfig.RequireHandshake = envconfig.RequireHandshakeOn
  205. defer func() { envconfig.RequireHandshake = old }()
  206. lis, err := net.Listen("tcp", "localhost:0")
  207. if err != nil {
  208. t.Fatalf("Error while listening. Err: %v", err)
  209. }
  210. defer lis.Close()
  211. done := make(chan struct{})
  212. sent := make(chan struct{})
  213. dialDone := make(chan struct{})
  214. go func() { // Launch the server.
  215. defer func() {
  216. close(done)
  217. }()
  218. conn, err := lis.Accept()
  219. if err != nil {
  220. t.Errorf("Error while accepting. Err: %v", err)
  221. return
  222. }
  223. defer conn.Close()
  224. // Sleep for a little bit to make sure that Dial on client
  225. // side blocks until settings are received.
  226. time.Sleep(100 * time.Millisecond)
  227. framer := http2.NewFramer(conn, conn)
  228. close(sent)
  229. if err := framer.WriteSettings(http2.Setting{}); err != nil {
  230. t.Errorf("Error while writing settings. Err: %v", err)
  231. return
  232. }
  233. <-dialDone // Close conn only after dial returns.
  234. }()
  235. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  236. defer cancel()
  237. client, err := DialContext(ctx, lis.Addr().String(), WithInsecure(), WithBlock())
  238. close(dialDone)
  239. if err != nil {
  240. t.Fatalf("Error while dialing. Err: %v", err)
  241. }
  242. defer client.Close()
  243. select {
  244. case <-sent:
  245. default:
  246. t.Fatalf("Dial returned before server settings were sent")
  247. }
  248. <-done
  249. }
  250. func (s) TestDialWaitsForServerSettingsAndFails(t *testing.T) {
  251. // Restore current setting after test.
  252. old := envconfig.RequireHandshake
  253. defer func() { envconfig.RequireHandshake = old }()
  254. for _, setting := range allReqHSSettings {
  255. envconfig.RequireHandshake = setting
  256. lis, err := net.Listen("tcp", "localhost:0")
  257. if err != nil {
  258. t.Fatalf("Error while listening. Err: %v", err)
  259. }
  260. done := make(chan struct{})
  261. numConns := 0
  262. go func() { // Launch the server.
  263. defer func() {
  264. close(done)
  265. }()
  266. for {
  267. conn, err := lis.Accept()
  268. if err != nil {
  269. break
  270. }
  271. numConns++
  272. defer conn.Close()
  273. }
  274. }()
  275. ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
  276. defer cancel()
  277. client, err := DialContext(ctx,
  278. lis.Addr().String(),
  279. WithInsecure(),
  280. WithWaitForHandshake(),
  281. WithBlock(),
  282. withBackoff(noBackoff{}),
  283. withMinConnectDeadline(func() time.Duration { return time.Second / 4 }))
  284. lis.Close()
  285. if err == nil {
  286. client.Close()
  287. t.Fatalf("Unexpected success (err=nil) while dialing")
  288. }
  289. if err != context.DeadlineExceeded {
  290. t.Fatalf("DialContext(_) = %v; want context.DeadlineExceeded", err)
  291. }
  292. if numConns < 2 {
  293. t.Fatalf("dial attempts: %v; want > 1", numConns)
  294. }
  295. <-done
  296. }
  297. }
  298. func (s) TestDialWaitsForServerSettingsViaEnvAndFails(t *testing.T) {
  299. // Set default behavior and restore current setting after test.
  300. old := envconfig.RequireHandshake
  301. envconfig.RequireHandshake = envconfig.RequireHandshakeOn
  302. defer func() { envconfig.RequireHandshake = old }()
  303. lis, err := net.Listen("tcp", "localhost:0")
  304. if err != nil {
  305. t.Fatalf("Error while listening. Err: %v", err)
  306. }
  307. done := make(chan struct{})
  308. numConns := 0
  309. go func() { // Launch the server.
  310. defer func() {
  311. close(done)
  312. }()
  313. for {
  314. conn, err := lis.Accept()
  315. if err != nil {
  316. break
  317. }
  318. numConns++
  319. defer conn.Close()
  320. }
  321. }()
  322. ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
  323. defer cancel()
  324. client, err := DialContext(ctx,
  325. lis.Addr().String(),
  326. WithInsecure(),
  327. WithBlock(),
  328. withBackoff(noBackoff{}),
  329. withMinConnectDeadline(func() time.Duration { return time.Second / 4 }))
  330. lis.Close()
  331. if err == nil {
  332. client.Close()
  333. t.Fatalf("Unexpected success (err=nil) while dialing")
  334. }
  335. if err != context.DeadlineExceeded {
  336. t.Fatalf("DialContext(_) = %v; want context.DeadlineExceeded", err)
  337. }
  338. if numConns < 2 {
  339. t.Fatalf("dial attempts: %v; want > 1", numConns)
  340. }
  341. <-done
  342. }
  343. func (s) TestDialDoesNotWaitForServerSettings(t *testing.T) {
  344. // Restore current setting after test.
  345. old := envconfig.RequireHandshake
  346. defer func() { envconfig.RequireHandshake = old }()
  347. envconfig.RequireHandshake = envconfig.RequireHandshakeOff
  348. lis, err := net.Listen("tcp", "localhost:0")
  349. if err != nil {
  350. t.Fatalf("Error while listening. Err: %v", err)
  351. }
  352. defer lis.Close()
  353. done := make(chan struct{})
  354. dialDone := make(chan struct{})
  355. go func() { // Launch the server.
  356. defer func() {
  357. close(done)
  358. }()
  359. conn, err := lis.Accept()
  360. if err != nil {
  361. t.Errorf("Error while accepting. Err: %v", err)
  362. return
  363. }
  364. defer conn.Close()
  365. <-dialDone // Close conn only after dial returns.
  366. }()
  367. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  368. defer cancel()
  369. client, err := DialContext(ctx, lis.Addr().String(), WithInsecure(), WithBlock())
  370. if err != nil {
  371. t.Fatalf("DialContext returned err =%v; want nil", err)
  372. }
  373. defer client.Close()
  374. if state := client.GetState(); state != connectivity.Ready {
  375. t.Fatalf("client.GetState() = %v; want connectivity.Ready", state)
  376. }
  377. close(dialDone)
  378. }
  379. // 1. Client connects to a server that doesn't send preface.
  380. // 2. After minConnectTimeout(500 ms here), client disconnects and retries.
  381. // 3. The new server sends its preface.
  382. // 4. Client doesn't kill the connection this time.
  383. func (s) TestCloseConnectionWhenServerPrefaceNotReceived(t *testing.T) {
  384. // Restore current setting after test.
  385. old := envconfig.RequireHandshake
  386. defer func() { envconfig.RequireHandshake = old }()
  387. envconfig.RequireHandshake = envconfig.RequireHandshakeOn
  388. lis, err := net.Listen("tcp", "localhost:0")
  389. if err != nil {
  390. t.Fatalf("Error while listening. Err: %v", err)
  391. }
  392. var (
  393. conn2 net.Conn
  394. over uint32
  395. )
  396. defer func() {
  397. lis.Close()
  398. // conn2 shouldn't be closed until the client has
  399. // observed a successful test.
  400. if conn2 != nil {
  401. conn2.Close()
  402. }
  403. }()
  404. done := make(chan struct{})
  405. accepted := make(chan struct{})
  406. go func() { // Launch the server.
  407. defer close(done)
  408. conn1, err := lis.Accept()
  409. if err != nil {
  410. t.Errorf("Error while accepting. Err: %v", err)
  411. return
  412. }
  413. defer conn1.Close()
  414. // Don't send server settings and the client should close the connection and try again.
  415. conn2, err = lis.Accept() // Accept a reconnection request from client.
  416. if err != nil {
  417. t.Errorf("Error while accepting. Err: %v", err)
  418. return
  419. }
  420. close(accepted)
  421. framer := http2.NewFramer(conn2, conn2)
  422. if err = framer.WriteSettings(http2.Setting{}); err != nil {
  423. t.Errorf("Error while writing settings. Err: %v", err)
  424. return
  425. }
  426. b := make([]byte, 8)
  427. for {
  428. _, err = conn2.Read(b)
  429. if err == nil {
  430. continue
  431. }
  432. if atomic.LoadUint32(&over) == 1 {
  433. // The connection stayed alive for the timer.
  434. // Success.
  435. return
  436. }
  437. t.Errorf("Unexpected error while reading. Err: %v, want timeout error", err)
  438. break
  439. }
  440. }()
  441. client, err := Dial(lis.Addr().String(), WithInsecure(), withMinConnectDeadline(func() time.Duration { return time.Millisecond * 500 }))
  442. if err != nil {
  443. t.Fatalf("Error while dialing. Err: %v", err)
  444. }
  445. // wait for connection to be accepted on the server.
  446. timer := time.NewTimer(time.Second * 10)
  447. select {
  448. case <-accepted:
  449. case <-timer.C:
  450. t.Fatalf("Client didn't make another connection request in time.")
  451. }
  452. // Make sure the connection stays alive for sometime.
  453. time.Sleep(time.Second)
  454. atomic.StoreUint32(&over, 1)
  455. client.Close()
  456. <-done
  457. }
  458. func (s) TestBackoffWhenNoServerPrefaceReceived(t *testing.T) {
  459. lis, err := net.Listen("tcp", "localhost:0")
  460. if err != nil {
  461. t.Fatalf("Error while listening. Err: %v", err)
  462. }
  463. defer lis.Close()
  464. done := make(chan struct{})
  465. go func() { // Launch the server.
  466. defer func() {
  467. close(done)
  468. }()
  469. conn, err := lis.Accept() // Accept the connection only to close it immediately.
  470. if err != nil {
  471. t.Errorf("Error while accepting. Err: %v", err)
  472. return
  473. }
  474. prevAt := time.Now()
  475. conn.Close()
  476. var prevDuration time.Duration
  477. // Make sure the retry attempts are backed off properly.
  478. for i := 0; i < 3; i++ {
  479. conn, err := lis.Accept()
  480. if err != nil {
  481. t.Errorf("Error while accepting. Err: %v", err)
  482. return
  483. }
  484. meow := time.Now()
  485. conn.Close()
  486. dr := meow.Sub(prevAt)
  487. if dr <= prevDuration {
  488. t.Errorf("Client backoff did not increase with retries. Previous duration: %v, current duration: %v", prevDuration, dr)
  489. return
  490. }
  491. prevDuration = dr
  492. prevAt = meow
  493. }
  494. }()
  495. client, err := Dial(lis.Addr().String(), WithInsecure())
  496. if err != nil {
  497. t.Fatalf("Error while dialing. Err: %v", err)
  498. }
  499. defer client.Close()
  500. <-done
  501. }
  502. func (s) TestConnectivityStates(t *testing.T) {
  503. servers, resolver, cleanup := startServers(t, 2, math.MaxUint32)
  504. defer cleanup()
  505. cc, err := Dial("passthrough:///foo.bar.com", WithBalancer(RoundRobin(resolver)), WithInsecure())
  506. if err != nil {
  507. t.Fatalf("Dial(\"foo.bar.com\", WithBalancer(_)) = _, %v, want _ <nil>", err)
  508. }
  509. defer cc.Close()
  510. wantState := connectivity.Ready
  511. if state, ok := assertState(wantState, cc); !ok {
  512. t.Fatalf("asserState(%s) = %s, false, want %s, true", wantState, state, wantState)
  513. }
  514. // Send an update to delete the server connection (tearDown addrConn).
  515. update := []*naming.Update{
  516. {
  517. Op: naming.Delete,
  518. Addr: "localhost:" + servers[0].port,
  519. },
  520. }
  521. resolver.w.inject(update)
  522. wantState = connectivity.TransientFailure
  523. if state, ok := assertState(wantState, cc); !ok {
  524. t.Fatalf("asserState(%s) = %s, false, want %s, true", wantState, state, wantState)
  525. }
  526. update[0] = &naming.Update{
  527. Op: naming.Add,
  528. Addr: "localhost:" + servers[1].port,
  529. }
  530. resolver.w.inject(update)
  531. wantState = connectivity.Ready
  532. if state, ok := assertState(wantState, cc); !ok {
  533. t.Fatalf("asserState(%s) = %s, false, want %s, true", wantState, state, wantState)
  534. }
  535. }
  536. func (s) TestWithTimeout(t *testing.T) {
  537. conn, err := Dial("passthrough:///Non-Existent.Server:80", WithTimeout(time.Millisecond), WithBlock(), WithInsecure())
  538. if err == nil {
  539. conn.Close()
  540. }
  541. if err != context.DeadlineExceeded {
  542. t.Fatalf("Dial(_, _) = %v, %v, want %v", conn, err, context.DeadlineExceeded)
  543. }
  544. }
  545. func (s) TestWithTransportCredentialsTLS(t *testing.T) {
  546. ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond)
  547. defer cancel()
  548. creds, err := credentials.NewClientTLSFromFile(testdata.Path("ca.pem"), "x.test.youtube.com")
  549. if err != nil {
  550. t.Fatalf("Failed to create credentials %v", err)
  551. }
  552. conn, err := DialContext(ctx, "passthrough:///Non-Existent.Server:80", WithTransportCredentials(creds), WithBlock())
  553. if err == nil {
  554. conn.Close()
  555. }
  556. if err != context.DeadlineExceeded {
  557. t.Fatalf("Dial(_, _) = %v, %v, want %v", conn, err, context.DeadlineExceeded)
  558. }
  559. }
  560. func (s) TestDefaultAuthority(t *testing.T) {
  561. target := "Non-Existent.Server:8080"
  562. conn, err := Dial(target, WithInsecure())
  563. if err != nil {
  564. t.Fatalf("Dial(_, _) = _, %v, want _, <nil>", err)
  565. }
  566. defer conn.Close()
  567. if conn.authority != target {
  568. t.Fatalf("%v.authority = %v, want %v", conn, conn.authority, target)
  569. }
  570. }
  571. func (s) TestTLSServerNameOverwrite(t *testing.T) {
  572. overwriteServerName := "over.write.server.name"
  573. creds, err := credentials.NewClientTLSFromFile(testdata.Path("ca.pem"), overwriteServerName)
  574. if err != nil {
  575. t.Fatalf("Failed to create credentials %v", err)
  576. }
  577. conn, err := Dial("passthrough:///Non-Existent.Server:80", WithTransportCredentials(creds))
  578. if err != nil {
  579. t.Fatalf("Dial(_, _) = _, %v, want _, <nil>", err)
  580. }
  581. defer conn.Close()
  582. if conn.authority != overwriteServerName {
  583. t.Fatalf("%v.authority = %v, want %v", conn, conn.authority, overwriteServerName)
  584. }
  585. }
  586. func (s) TestWithAuthority(t *testing.T) {
  587. overwriteServerName := "over.write.server.name"
  588. conn, err := Dial("passthrough:///Non-Existent.Server:80", WithInsecure(), WithAuthority(overwriteServerName))
  589. if err != nil {
  590. t.Fatalf("Dial(_, _) = _, %v, want _, <nil>", err)
  591. }
  592. defer conn.Close()
  593. if conn.authority != overwriteServerName {
  594. t.Fatalf("%v.authority = %v, want %v", conn, conn.authority, overwriteServerName)
  595. }
  596. }
  597. func (s) TestWithAuthorityAndTLS(t *testing.T) {
  598. overwriteServerName := "over.write.server.name"
  599. creds, err := credentials.NewClientTLSFromFile(testdata.Path("ca.pem"), overwriteServerName)
  600. if err != nil {
  601. t.Fatalf("Failed to create credentials %v", err)
  602. }
  603. conn, err := Dial("passthrough:///Non-Existent.Server:80", WithTransportCredentials(creds), WithAuthority("no.effect.authority"))
  604. if err != nil {
  605. t.Fatalf("Dial(_, _) = _, %v, want _, <nil>", err)
  606. }
  607. defer conn.Close()
  608. if conn.authority != overwriteServerName {
  609. t.Fatalf("%v.authority = %v, want %v", conn, conn.authority, overwriteServerName)
  610. }
  611. }
  612. // When creating a transport configured with n addresses, only calculate the
  613. // backoff once per "round" of attempts instead of once per address (n times
  614. // per "round" of attempts).
  615. func (s) TestDial_OneBackoffPerRetryGroup(t *testing.T) {
  616. var attempts uint32
  617. getMinConnectTimeout := func() time.Duration {
  618. if atomic.AddUint32(&attempts, 1) == 1 {
  619. // Once all addresses are exhausted, hang around and wait for the
  620. // client.Close to happen rather than re-starting a new round of
  621. // attempts.
  622. return time.Hour
  623. }
  624. t.Error("only one attempt backoff calculation, but got more")
  625. return 0
  626. }
  627. ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
  628. defer cancel()
  629. lis1, err := net.Listen("tcp", "localhost:0")
  630. if err != nil {
  631. t.Fatalf("Error while listening. Err: %v", err)
  632. }
  633. defer lis1.Close()
  634. lis2, err := net.Listen("tcp", "localhost:0")
  635. if err != nil {
  636. t.Fatalf("Error while listening. Err: %v", err)
  637. }
  638. defer lis2.Close()
  639. server1Done := make(chan struct{})
  640. server2Done := make(chan struct{})
  641. // Launch server 1.
  642. go func() {
  643. conn, err := lis1.Accept()
  644. if err != nil {
  645. t.Error(err)
  646. return
  647. }
  648. conn.Close()
  649. close(server1Done)
  650. }()
  651. // Launch server 2.
  652. go func() {
  653. conn, err := lis2.Accept()
  654. if err != nil {
  655. t.Error(err)
  656. return
  657. }
  658. conn.Close()
  659. close(server2Done)
  660. }()
  661. rb := manual.NewBuilderWithScheme("whatever")
  662. rb.InitialState(resolver.State{Addresses: []resolver.Address{
  663. {Addr: lis1.Addr().String()},
  664. {Addr: lis2.Addr().String()},
  665. }})
  666. client, err := DialContext(ctx, "this-gets-overwritten",
  667. WithInsecure(),
  668. WithBalancerName(stateRecordingBalancerName),
  669. withResolverBuilder(rb),
  670. withMinConnectDeadline(getMinConnectTimeout))
  671. if err != nil {
  672. t.Fatal(err)
  673. }
  674. defer client.Close()
  675. timeout := time.After(15 * time.Second)
  676. select {
  677. case <-timeout:
  678. t.Fatal("timed out waiting for test to finish")
  679. case <-server1Done:
  680. }
  681. select {
  682. case <-timeout:
  683. t.Fatal("timed out waiting for test to finish")
  684. case <-server2Done:
  685. }
  686. }
  687. func (s) TestDialContextCancel(t *testing.T) {
  688. ctx, cancel := context.WithCancel(context.Background())
  689. cancel()
  690. if _, err := DialContext(ctx, "Non-Existent.Server:80", WithBlock(), WithInsecure()); err != context.Canceled {
  691. t.Fatalf("DialContext(%v, _) = _, %v, want _, %v", ctx, err, context.Canceled)
  692. }
  693. }
  694. type failFastError struct{}
  695. func (failFastError) Error() string { return "failfast" }
  696. func (failFastError) Temporary() bool { return false }
  697. func (s) TestDialContextFailFast(t *testing.T) {
  698. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  699. defer cancel()
  700. failErr := failFastError{}
  701. dialer := func(string, time.Duration) (net.Conn, error) {
  702. return nil, failErr
  703. }
  704. _, err := DialContext(ctx, "Non-Existent.Server:80", WithBlock(), WithInsecure(), WithDialer(dialer), FailOnNonTempDialError(true))
  705. if terr, ok := err.(transport.ConnectionError); !ok || terr.Origin() != failErr {
  706. t.Fatalf("DialContext() = _, %v, want _, %v", err, failErr)
  707. }
  708. }
  709. // blockingBalancer mimics the behavior of balancers whose initialization takes a long time.
  710. // In this test, reading from blockingBalancer.Notify() blocks forever.
  711. type blockingBalancer struct {
  712. ch chan []Address
  713. }
  714. func newBlockingBalancer() Balancer {
  715. return &blockingBalancer{ch: make(chan []Address)}
  716. }
  717. func (b *blockingBalancer) Start(target string, config BalancerConfig) error {
  718. return nil
  719. }
  720. func (b *blockingBalancer) Up(addr Address) func(error) {
  721. return nil
  722. }
  723. func (b *blockingBalancer) Get(ctx context.Context, opts BalancerGetOptions) (addr Address, put func(), err error) {
  724. return Address{}, nil, nil
  725. }
  726. func (b *blockingBalancer) Notify() <-chan []Address {
  727. return b.ch
  728. }
  729. func (b *blockingBalancer) Close() error {
  730. close(b.ch)
  731. return nil
  732. }
  733. func (s) TestDialWithBlockingBalancer(t *testing.T) {
  734. ctx, cancel := context.WithCancel(context.Background())
  735. dialDone := make(chan struct{})
  736. go func() {
  737. DialContext(ctx, "Non-Existent.Server:80", WithBlock(), WithInsecure(), WithBalancer(newBlockingBalancer()))
  738. close(dialDone)
  739. }()
  740. cancel()
  741. <-dialDone
  742. }
  743. // securePerRPCCredentials always requires transport security.
  744. type securePerRPCCredentials struct{}
  745. func (c securePerRPCCredentials) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) {
  746. return nil, nil
  747. }
  748. func (c securePerRPCCredentials) RequireTransportSecurity() bool {
  749. return true
  750. }
  751. func (s) TestCredentialsMisuse(t *testing.T) {
  752. tlsCreds, err := credentials.NewClientTLSFromFile(testdata.Path("ca.pem"), "x.test.youtube.com")
  753. if err != nil {
  754. t.Fatalf("Failed to create authenticator %v", err)
  755. }
  756. // Two conflicting credential configurations
  757. if _, err := Dial("passthrough:///Non-Existent.Server:80", WithTransportCredentials(tlsCreds), WithBlock(), WithInsecure()); err != errCredentialsConflict {
  758. t.Fatalf("Dial(_, _) = _, %v, want _, %v", err, errCredentialsConflict)
  759. }
  760. // security info on insecure connection
  761. if _, err := Dial("passthrough:///Non-Existent.Server:80", WithPerRPCCredentials(securePerRPCCredentials{}), WithBlock(), WithInsecure()); err != errTransportCredentialsMissing {
  762. t.Fatalf("Dial(_, _) = _, %v, want _, %v", err, errTransportCredentialsMissing)
  763. }
  764. }
  765. func (s) TestWithBackoffConfigDefault(t *testing.T) {
  766. testBackoffConfigSet(t, &DefaultBackoffConfig)
  767. }
  768. func (s) TestWithBackoffConfig(t *testing.T) {
  769. b := BackoffConfig{MaxDelay: DefaultBackoffConfig.MaxDelay / 2}
  770. expected := b
  771. testBackoffConfigSet(t, &expected, WithBackoffConfig(b))
  772. }
  773. func (s) TestWithBackoffMaxDelay(t *testing.T) {
  774. md := DefaultBackoffConfig.MaxDelay / 2
  775. expected := BackoffConfig{MaxDelay: md}
  776. testBackoffConfigSet(t, &expected, WithBackoffMaxDelay(md))
  777. }
  778. func testBackoffConfigSet(t *testing.T, expected *BackoffConfig, opts ...DialOption) {
  779. opts = append(opts, WithInsecure())
  780. conn, err := Dial("passthrough:///foo:80", opts...)
  781. if err != nil {
  782. t.Fatalf("unexpected error dialing connection: %v", err)
  783. }
  784. defer conn.Close()
  785. if conn.dopts.bs == nil {
  786. t.Fatalf("backoff config not set")
  787. }
  788. actual, ok := conn.dopts.bs.(backoff.Exponential)
  789. if !ok {
  790. t.Fatalf("unexpected type of backoff config: %#v", conn.dopts.bs)
  791. }
  792. expectedValue := backoff.Exponential{
  793. MaxDelay: expected.MaxDelay,
  794. }
  795. if actual != expectedValue {
  796. t.Fatalf("unexpected backoff config on connection: %v, want %v", actual, expected)
  797. }
  798. }
  799. // emptyBalancer returns an empty set of servers.
  800. type emptyBalancer struct {
  801. ch chan []Address
  802. }
  803. func newEmptyBalancer() Balancer {
  804. return &emptyBalancer{ch: make(chan []Address, 1)}
  805. }
  806. func (b *emptyBalancer) Start(_ string, _ BalancerConfig) error {
  807. b.ch <- nil
  808. return nil
  809. }
  810. func (b *emptyBalancer) Up(_ Address) func(error) {
  811. return nil
  812. }
  813. func (b *emptyBalancer) Get(_ context.Context, _ BalancerGetOptions) (Address, func(), error) {
  814. return Address{}, nil, nil
  815. }
  816. func (b *emptyBalancer) Notify() <-chan []Address {
  817. return b.ch
  818. }
  819. func (b *emptyBalancer) Close() error {
  820. close(b.ch)
  821. return nil
  822. }
  823. func (s) TestNonblockingDialWithEmptyBalancer(t *testing.T) {
  824. ctx, cancel := context.WithCancel(context.Background())
  825. defer cancel()
  826. dialDone := make(chan error)
  827. go func() {
  828. dialDone <- func() error {
  829. conn, err := DialContext(ctx, "Non-Existent.Server:80", WithInsecure(), WithBalancer(newEmptyBalancer()))
  830. if err != nil {
  831. return err
  832. }
  833. return conn.Close()
  834. }()
  835. }()
  836. if err := <-dialDone; err != nil {
  837. t.Fatalf("unexpected error dialing connection: %s", err)
  838. }
  839. }
  840. func (s) TestResolverServiceConfigBeforeAddressNotPanic(t *testing.T) {
  841. r, rcleanup := manual.GenerateAndRegisterManualResolver()
  842. defer rcleanup()
  843. cc, err := Dial(r.Scheme()+":///test.server", WithInsecure())
  844. if err != nil {
  845. t.Fatalf("failed to dial: %v", err)
  846. }
  847. defer cc.Close()
  848. // SwitchBalancer before NewAddress. There was no balancer created, this
  849. // makes sure we don't call close on nil balancerWrapper.
  850. r.UpdateState(resolver.State{ServiceConfig: `{"loadBalancingPolicy": "round_robin"}`}) // This should not panic.
  851. time.Sleep(time.Second) // Sleep to make sure the service config is handled by ClientConn.
  852. }
  853. func (s) TestResolverServiceConfigWhileClosingNotPanic(t *testing.T) {
  854. for i := 0; i < 10; i++ { // Run this multiple times to make sure it doesn't panic.
  855. r, rcleanup := manual.GenerateAndRegisterManualResolver()
  856. defer rcleanup()
  857. cc, err := Dial(r.Scheme()+":///test.server", WithInsecure())
  858. if err != nil {
  859. t.Fatalf("failed to dial: %v", err)
  860. }
  861. // Send a new service config while closing the ClientConn.
  862. go cc.Close()
  863. go r.UpdateState(resolver.State{ServiceConfig: `{"loadBalancingPolicy": "round_robin"}`}) // This should not panic.
  864. }
  865. }
  866. func (s) TestResolverEmptyUpdateNotPanic(t *testing.T) {
  867. r, rcleanup := manual.GenerateAndRegisterManualResolver()
  868. defer rcleanup()
  869. cc, err := Dial(r.Scheme()+":///test.server", WithInsecure())
  870. if err != nil {
  871. t.Fatalf("failed to dial: %v", err)
  872. }
  873. defer cc.Close()
  874. // This make sure we don't create addrConn with empty address list.
  875. r.UpdateState(resolver.State{}) // This should not panic.
  876. time.Sleep(time.Second) // Sleep to make sure the service config is handled by ClientConn.
  877. }
  878. func (s) TestClientUpdatesParamsAfterGoAway(t *testing.T) {
  879. lis, err := net.Listen("tcp", "localhost:0")
  880. if err != nil {
  881. t.Fatalf("Failed to listen. Err: %v", err)
  882. }
  883. defer lis.Close()
  884. connected := make(chan struct{})
  885. go func() {
  886. conn, err := lis.Accept()
  887. if err != nil {
  888. t.Errorf("error accepting connection: %v", err)
  889. return
  890. }
  891. defer conn.Close()
  892. f := http2.NewFramer(conn, conn)
  893. // Start a goroutine to read from the conn to prevent the client from
  894. // blocking after it writes its preface.
  895. go func() {
  896. for {
  897. if _, err := f.ReadFrame(); err != nil {
  898. return
  899. }
  900. }
  901. }()
  902. if err := f.WriteSettings(http2.Setting{}); err != nil {
  903. t.Errorf("error writing settings: %v", err)
  904. return
  905. }
  906. <-connected
  907. if err := f.WriteGoAway(0, http2.ErrCodeEnhanceYourCalm, []byte("too_many_pings")); err != nil {
  908. t.Errorf("error writing GOAWAY: %v", err)
  909. return
  910. }
  911. }()
  912. addr := lis.Addr().String()
  913. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  914. defer cancel()
  915. cc, err := DialContext(ctx, addr, WithBlock(), WithInsecure(), WithKeepaliveParams(keepalive.ClientParameters{
  916. Time: 10 * time.Second,
  917. Timeout: 100 * time.Millisecond,
  918. PermitWithoutStream: true,
  919. }))
  920. if err != nil {
  921. t.Fatalf("Dial(%s, _) = _, %v, want _, <nil>", addr, err)
  922. }
  923. defer cc.Close()
  924. close(connected)
  925. for {
  926. time.Sleep(10 * time.Millisecond)
  927. cc.mu.RLock()
  928. v := cc.mkp.Time
  929. if v == 20*time.Second {
  930. // Success
  931. cc.mu.RUnlock()
  932. return
  933. }
  934. if ctx.Err() != nil {
  935. // Timeout
  936. t.Fatalf("cc.dopts.copts.Keepalive.Time = %v , want 20s", v)
  937. }
  938. cc.mu.RUnlock()
  939. }
  940. }
  941. func (s) TestDisableServiceConfigOption(t *testing.T) {
  942. r, cleanup := manual.GenerateAndRegisterManualResolver()
  943. defer cleanup()
  944. addr := r.Scheme() + ":///non.existent"
  945. cc, err := Dial(addr, WithInsecure(), WithDisableServiceConfig())
  946. if err != nil {
  947. t.Fatalf("Dial(%s, _) = _, %v, want _, <nil>", addr, err)
  948. }
  949. defer cc.Close()
  950. r.UpdateState(resolver.State{ServiceConfig: `{
  951. "methodConfig": [
  952. {
  953. "name": [
  954. {
  955. "service": "foo",
  956. "method": "Bar"
  957. }
  958. ],
  959. "waitForReady": true
  960. }
  961. ]
  962. }`})
  963. time.Sleep(1 * time.Second)
  964. m := cc.GetMethodConfig("/foo/Bar")
  965. if m.WaitForReady != nil {
  966. t.Fatalf("want: method (\"/foo/bar/\") config to be empty, got: %v", m)
  967. }
  968. }
  969. func (s) TestGetClientConnTarget(t *testing.T) {
  970. addr := "nonexist:///non.existent"
  971. cc, err := Dial(addr, WithInsecure())
  972. if err != nil {
  973. t.Fatalf("Dial(%s, _) = _, %v, want _, <nil>", addr, err)
  974. }
  975. defer cc.Close()
  976. if cc.Target() != addr {
  977. t.Fatalf("Target() = %s, want %s", cc.Target(), addr)
  978. }
  979. }
  980. type backoffForever struct{}
  981. func (b backoffForever) Backoff(int) time.Duration { return time.Duration(math.MaxInt64) }
  982. func (s) TestResetConnectBackoff(t *testing.T) {
  983. dials := make(chan struct{})
  984. defer func() { // If we fail, let the http2client break out of dialing.
  985. select {
  986. case <-dials:
  987. default:
  988. }
  989. }()
  990. dialer := func(string, time.Duration) (net.Conn, error) {
  991. dials <- struct{}{}
  992. return nil, errors.New("failed to fake dial")
  993. }
  994. cc, err := Dial("any", WithInsecure(), WithDialer(dialer), withBackoff(backoffForever{}))
  995. if err != nil {
  996. t.Fatalf("Dial() = _, %v; want _, nil", err)
  997. }
  998. defer cc.Close()
  999. select {
  1000. case <-dials:
  1001. case <-time.NewTimer(10 * time.Second).C:
  1002. t.Fatal("Failed to call dial within 10s")
  1003. }
  1004. select {
  1005. case <-dials:
  1006. t.Fatal("Dial called unexpectedly before resetting backoff")
  1007. case <-time.NewTimer(100 * time.Millisecond).C:
  1008. }
  1009. cc.ResetConnectBackoff()
  1010. select {
  1011. case <-dials:
  1012. case <-time.NewTimer(10 * time.Second).C:
  1013. t.Fatal("Failed to call dial within 10s after resetting backoff")
  1014. }
  1015. }
  1016. func (s) TestBackoffCancel(t *testing.T) {
  1017. dialStrCh := make(chan string)
  1018. cc, err := Dial("any", WithInsecure(), WithDialer(func(t string, _ time.Duration) (net.Conn, error) {
  1019. dialStrCh <- t
  1020. return nil, fmt.Errorf("test dialer, always error")
  1021. }))
  1022. if err != nil {
  1023. t.Fatalf("Failed to create ClientConn: %v", err)
  1024. }
  1025. <-dialStrCh
  1026. cc.Close()
  1027. // Should not leak. May need -count 5000 to exercise.
  1028. }
  1029. // UpdateAddresses should cause the next reconnect to begin from the top of the
  1030. // list if the connection is not READY.
  1031. func (s) TestUpdateAddresses_RetryFromFirstAddr(t *testing.T) {
  1032. lis1, err := net.Listen("tcp", "localhost:0")
  1033. if err != nil {
  1034. t.Fatalf("Error while listening. Err: %v", err)
  1035. }
  1036. defer lis1.Close()
  1037. lis2, err := net.Listen("tcp", "localhost:0")
  1038. if err != nil {
  1039. t.Fatalf("Error while listening. Err: %v", err)
  1040. }
  1041. defer lis2.Close()
  1042. lis3, err := net.Listen("tcp", "localhost:0")
  1043. if err != nil {
  1044. t.Fatalf("Error while listening. Err: %v", err)
  1045. }
  1046. defer lis3.Close()
  1047. closeServer2 := make(chan struct{})
  1048. server1ContactedFirstTime := make(chan struct{})
  1049. server1ContactedSecondTime := make(chan struct{})
  1050. server2ContactedFirstTime := make(chan struct{})
  1051. server2ContactedSecondTime := make(chan struct{})
  1052. server3Contacted := make(chan struct{})
  1053. // Launch server 1.
  1054. go func() {
  1055. // First, let's allow the initial connection to go READY. We need to do
  1056. // this because tryUpdateAddrs only works after there's some non-nil
  1057. // address on the ac, and curAddress is only set after READY.
  1058. conn1, err := lis1.Accept()
  1059. if err != nil {
  1060. t.Error(err)
  1061. return
  1062. }
  1063. go keepReading(conn1)
  1064. framer := http2.NewFramer(conn1, conn1)
  1065. if err := framer.WriteSettings(http2.Setting{}); err != nil {
  1066. t.Errorf("Error while writing settings frame. %v", err)
  1067. return
  1068. }
  1069. // nextStateNotifier() is updated after balancerBuilder.Build(), which is
  1070. // called by grpc.Dial. It's safe to do it here because lis1.Accept blocks
  1071. // until balancer is built to process the addresses.
  1072. stateNotifications := testBalancerBuilder.nextStateNotifier()
  1073. // Wait for the transport to become ready.
  1074. for s := range stateNotifications {
  1075. if s == connectivity.Ready {
  1076. break
  1077. }
  1078. }
  1079. // Once it's ready, curAddress has been set. So let's close this
  1080. // connection prompting the first reconnect cycle.
  1081. conn1.Close()
  1082. // Accept and immediately close, causing it to go to server2.
  1083. conn2, err := lis1.Accept()
  1084. if err != nil {
  1085. t.Error(err)
  1086. return
  1087. }
  1088. close(server1ContactedFirstTime)
  1089. conn2.Close()
  1090. // Hopefully it picks this server after tryUpdateAddrs.
  1091. lis1.Accept()
  1092. close(server1ContactedSecondTime)
  1093. }()
  1094. // Launch server 2.
  1095. go func() {
  1096. // Accept and then hang waiting for the test call tryUpdateAddrs and
  1097. // then signal to this server to close. After this server closes, it
  1098. // should start from the top instead of trying server2 or continuing
  1099. // to server3.
  1100. conn, err := lis2.Accept()
  1101. if err != nil {
  1102. t.Error(err)
  1103. return
  1104. }
  1105. close(server2ContactedFirstTime)
  1106. <-closeServer2
  1107. conn.Close()
  1108. // After tryUpdateAddrs, it should NOT try server2.
  1109. lis2.Accept()
  1110. close(server2ContactedSecondTime)
  1111. }()
  1112. // Launch server 3.
  1113. go func() {
  1114. // After tryUpdateAddrs, it should NOT try server3. (or any other time)
  1115. lis3.Accept()
  1116. close(server3Contacted)
  1117. }()
  1118. addrsList := []resolver.Address{
  1119. {Addr: lis1.Addr().String()},
  1120. {Addr: lis2.Addr().String()},
  1121. {Addr: lis3.Addr().String()},
  1122. }
  1123. rb := manual.NewBuilderWithScheme("whatever")
  1124. rb.InitialState(resolver.State{Addresses: addrsList})
  1125. client, err := Dial("this-gets-overwritten",
  1126. WithInsecure(),
  1127. WithWaitForHandshake(),
  1128. withResolverBuilder(rb),
  1129. withBackoff(noBackoff{}),
  1130. WithBalancerName(stateRecordingBalancerName),
  1131. withMinConnectDeadline(func() time.Duration { return time.Hour }))
  1132. if err != nil {
  1133. t.Fatal(err)
  1134. }
  1135. defer client.Close()
  1136. timeout := time.After(5 * time.Second)
  1137. // Wait for server1 to be contacted (which will immediately fail), then
  1138. // server2 (which will hang waiting for our signal).
  1139. select {
  1140. case <-server1ContactedFirstTime:
  1141. case <-timeout:
  1142. t.Fatal("timed out waiting for server1 to be contacted")
  1143. }
  1144. select {
  1145. case <-server2ContactedFirstTime:
  1146. case <-timeout:
  1147. t.Fatal("timed out waiting for server2 to be contacted")
  1148. }
  1149. // Grab the addrConn and call tryUpdateAddrs.
  1150. var ac *addrConn
  1151. client.mu.Lock()
  1152. for clientAC := range client.conns {
  1153. ac = clientAC
  1154. break
  1155. }
  1156. client.mu.Unlock()
  1157. ac.acbw.UpdateAddresses(addrsList)
  1158. // We've called tryUpdateAddrs - now let's make server2 close the
  1159. // connection and check that it goes back to server1 instead of continuing
  1160. // to server3 or trying server2 again.
  1161. close(closeServer2)
  1162. select {
  1163. case <-server1ContactedSecondTime:
  1164. case <-server2ContactedSecondTime:
  1165. t.Fatal("server2 was contacted a second time, but it after tryUpdateAddrs it should have re-started the list and tried server1")
  1166. case <-server3Contacted:
  1167. t.Fatal("server3 was contacted, but after tryUpdateAddrs it should have re-started the list and tried server1")
  1168. case <-timeout:
  1169. t.Fatal("timed out waiting for any server to be contacted after tryUpdateAddrs")
  1170. }
  1171. }
  1172. func (s) TestDefaultServiceConfig(t *testing.T) {
  1173. r, cleanup := manual.GenerateAndRegisterManualResolver()
  1174. defer cleanup()
  1175. addr := r.Scheme() + ":///non.existent"
  1176. js := `{
  1177. "methodConfig": [
  1178. {
  1179. "name": [
  1180. {
  1181. "service": "foo",
  1182. "method": "bar"
  1183. }
  1184. ],
  1185. "waitForReady": true
  1186. }
  1187. ]
  1188. }`
  1189. testInvalidDefaultServiceConfig(t)
  1190. testDefaultServiceConfigWhenResolverServiceConfigDisabled(t, r, addr, js)
  1191. testDefaultServiceConfigWhenResolverDoesNotReturnServiceConfig(t, r, addr, js)
  1192. testDefaultServiceConfigWhenResolverReturnInvalidServiceConfig(t, r, addr, js)
  1193. }
  1194. func verifyWaitForReadyEqualsTrue(cc *ClientConn) bool {
  1195. var i int
  1196. for i = 0; i < 10; i++ {
  1197. mc := cc.GetMethodConfig("/foo/bar")
  1198. if mc.WaitForReady != nil && *mc.WaitForReady == true {
  1199. break
  1200. }
  1201. time.Sleep(100 * time.Millisecond)
  1202. }
  1203. return i != 10
  1204. }
  1205. func testInvalidDefaultServiceConfig(t *testing.T) {
  1206. _, err := Dial("fake.com", WithInsecure(), WithDefaultServiceConfig(""))
  1207. if !strings.Contains(err.Error(), invalidDefaultServiceConfigErrPrefix) {
  1208. t.Fatalf("Dial got err: %v, want err contains: %v", err, invalidDefaultServiceConfigErrPrefix)
  1209. }
  1210. }
  1211. func testDefaultServiceConfigWhenResolverServiceConfigDisabled(t *testing.T, r resolver.Resolver, addr string, js string) {
  1212. cc, err := Dial(addr, WithInsecure(), WithDisableServiceConfig(), WithDefaultServiceConfig(js))
  1213. if err != nil {
  1214. t.Fatalf("Dial(%s, _) = _, %v, want _, <nil>", addr, err)
  1215. }
  1216. defer cc.Close()
  1217. // Resolver service config gets ignored since resolver service config is disabled.
  1218. r.(*manual.Resolver).UpdateState(resolver.State{
  1219. Addresses: []resolver.Address{{Addr: addr}},
  1220. ServiceConfig: "{}",
  1221. })
  1222. if !verifyWaitForReadyEqualsTrue(cc) {
  1223. t.Fatal("default service config failed to be applied after 1s")
  1224. }
  1225. }
  1226. func testDefaultServiceConfigWhenResolverDoesNotReturnServiceConfig(t *testing.T, r resolver.Resolver, addr string, js string) {
  1227. cc, err := Dial(addr, WithInsecure(), WithDefaultServiceConfig(js))
  1228. if err != nil {
  1229. t.Fatalf("Dial(%s, _) = _, %v, want _, <nil>", addr, err)
  1230. }
  1231. defer cc.Close()
  1232. r.(*manual.Resolver).UpdateState(resolver.State{
  1233. Addresses: []resolver.Address{{Addr: addr}},
  1234. })
  1235. if !verifyWaitForReadyEqualsTrue(cc) {
  1236. t.Fatal("default service config failed to be applied after 1s")
  1237. }
  1238. }
  1239. func testDefaultServiceConfigWhenResolverReturnInvalidServiceConfig(t *testing.T, r resolver.Resolver, addr string, js string) {
  1240. cc, err := Dial(addr, WithInsecure(), WithDefaultServiceConfig(js))
  1241. if err != nil {
  1242. t.Fatalf("Dial(%s, _) = _, %v, want _, <nil>", addr, err)
  1243. }
  1244. defer cc.Close()
  1245. r.(*manual.Resolver).UpdateState(resolver.State{
  1246. Addresses: []resolver.Address{{Addr: addr}},
  1247. ServiceConfig: "{something wrong,}",
  1248. })
  1249. if !verifyWaitForReadyEqualsTrue(cc) {
  1250. t.Fatal("default service config failed to be applied after 1s")
  1251. }
  1252. }