client_test.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608
  1. package sarama
  2. import (
  3. "io"
  4. "sync"
  5. "testing"
  6. "time"
  7. )
  8. func safeClose(t testing.TB, c io.Closer) {
  9. err := c.Close()
  10. if err != nil {
  11. t.Error(err)
  12. }
  13. }
  14. func TestSimpleClient(t *testing.T) {
  15. seedBroker := newMockBroker(t, 1)
  16. seedBroker.Returns(new(MetadataResponse))
  17. client, err := NewClient([]string{seedBroker.Addr()}, nil)
  18. if err != nil {
  19. t.Fatal(err)
  20. }
  21. seedBroker.Close()
  22. safeClose(t, client)
  23. }
  24. func TestCachedPartitions(t *testing.T) {
  25. seedBroker := newMockBroker(t, 1)
  26. replicas := []int32{3, 1, 5}
  27. isr := []int32{5, 1}
  28. metadataResponse := new(MetadataResponse)
  29. metadataResponse.AddBroker("localhost:12345", 2)
  30. metadataResponse.AddTopicPartition("my_topic", 0, 2, replicas, isr, ErrNoError)
  31. metadataResponse.AddTopicPartition("my_topic", 1, 2, replicas, isr, ErrLeaderNotAvailable)
  32. seedBroker.Returns(metadataResponse)
  33. config := NewConfig()
  34. config.Metadata.Retry.Max = 0
  35. c, err := NewClient([]string{seedBroker.Addr()}, config)
  36. if err != nil {
  37. t.Fatal(err)
  38. }
  39. client := c.(*client)
  40. // Verify they aren't cached the same
  41. allP := client.cachedPartitionsResults["my_topic"][allPartitions]
  42. writeP := client.cachedPartitionsResults["my_topic"][writablePartitions]
  43. if len(allP) == len(writeP) {
  44. t.Fatal("Invalid lengths!")
  45. }
  46. tmp := client.cachedPartitionsResults["my_topic"]
  47. // Verify we actually use the cache at all!
  48. tmp[allPartitions] = []int32{1, 2, 3, 4}
  49. client.cachedPartitionsResults["my_topic"] = tmp
  50. if 4 != len(client.cachedPartitions("my_topic", allPartitions)) {
  51. t.Fatal("Not using the cache!")
  52. }
  53. seedBroker.Close()
  54. safeClose(t, client)
  55. }
  56. func TestClientDoesntCachePartitionsForTopicsWithErrors(t *testing.T) {
  57. seedBroker := newMockBroker(t, 1)
  58. replicas := []int32{seedBroker.BrokerID()}
  59. metadataResponse := new(MetadataResponse)
  60. metadataResponse.AddBroker(seedBroker.Addr(), seedBroker.BrokerID())
  61. metadataResponse.AddTopicPartition("my_topic", 1, replicas[0], replicas, replicas, ErrNoError)
  62. metadataResponse.AddTopicPartition("my_topic", 2, replicas[0], replicas, replicas, ErrNoError)
  63. seedBroker.Returns(metadataResponse)
  64. config := NewConfig()
  65. config.Metadata.Retry.Max = 0
  66. client, err := NewClient([]string{seedBroker.Addr()}, config)
  67. if err != nil {
  68. t.Fatal(err)
  69. }
  70. metadataResponse = new(MetadataResponse)
  71. metadataResponse.AddTopic("unknown", ErrUnknownTopicOrPartition)
  72. seedBroker.Returns(metadataResponse)
  73. partitions, err := client.Partitions("unknown")
  74. if err != ErrUnknownTopicOrPartition {
  75. t.Error("Expected ErrUnknownTopicOrPartition, found", err)
  76. }
  77. if partitions != nil {
  78. t.Errorf("Should return nil as partition list, found %v", partitions)
  79. }
  80. // Should still use the cache of a known topic
  81. partitions, err = client.Partitions("my_topic")
  82. if err != nil {
  83. t.Errorf("Expected no error, found %v", err)
  84. }
  85. metadataResponse = new(MetadataResponse)
  86. metadataResponse.AddTopic("unknown", ErrUnknownTopicOrPartition)
  87. seedBroker.Returns(metadataResponse)
  88. // Should not use cache for unknown topic
  89. partitions, err = client.Partitions("unknown")
  90. if err != ErrUnknownTopicOrPartition {
  91. t.Error("Expected ErrUnknownTopicOrPartition, found", err)
  92. }
  93. if partitions != nil {
  94. t.Errorf("Should return nil as partition list, found %v", partitions)
  95. }
  96. seedBroker.Close()
  97. safeClose(t, client)
  98. }
  99. func TestClientSeedBrokers(t *testing.T) {
  100. seedBroker := newMockBroker(t, 1)
  101. metadataResponse := new(MetadataResponse)
  102. metadataResponse.AddBroker("localhost:12345", 2)
  103. seedBroker.Returns(metadataResponse)
  104. client, err := NewClient([]string{seedBroker.Addr()}, nil)
  105. if err != nil {
  106. t.Fatal(err)
  107. }
  108. seedBroker.Close()
  109. safeClose(t, client)
  110. }
  111. func TestClientMetadata(t *testing.T) {
  112. seedBroker := newMockBroker(t, 1)
  113. leader := newMockBroker(t, 5)
  114. replicas := []int32{3, 1, 5}
  115. isr := []int32{5, 1}
  116. metadataResponse := new(MetadataResponse)
  117. metadataResponse.AddBroker(leader.Addr(), leader.BrokerID())
  118. metadataResponse.AddTopicPartition("my_topic", 0, leader.BrokerID(), replicas, isr, ErrNoError)
  119. metadataResponse.AddTopicPartition("my_topic", 1, leader.BrokerID(), replicas, isr, ErrLeaderNotAvailable)
  120. seedBroker.Returns(metadataResponse)
  121. config := NewConfig()
  122. config.Metadata.Retry.Max = 0
  123. client, err := NewClient([]string{seedBroker.Addr()}, config)
  124. if err != nil {
  125. t.Fatal(err)
  126. }
  127. topics, err := client.Topics()
  128. if err != nil {
  129. t.Error(err)
  130. } else if len(topics) != 1 || topics[0] != "my_topic" {
  131. t.Error("Client returned incorrect topics:", topics)
  132. }
  133. parts, err := client.Partitions("my_topic")
  134. if err != nil {
  135. t.Error(err)
  136. } else if len(parts) != 2 || parts[0] != 0 || parts[1] != 1 {
  137. t.Error("Client returned incorrect partitions for my_topic:", parts)
  138. }
  139. parts, err = client.WritablePartitions("my_topic")
  140. if err != nil {
  141. t.Error(err)
  142. } else if len(parts) != 1 || parts[0] != 0 {
  143. t.Error("Client returned incorrect writable partitions for my_topic:", parts)
  144. }
  145. tst, err := client.Leader("my_topic", 0)
  146. if err != nil {
  147. t.Error(err)
  148. } else if tst.ID() != 5 {
  149. t.Error("Leader for my_topic had incorrect ID.")
  150. }
  151. replicas, err = client.Replicas("my_topic", 0)
  152. if err != nil {
  153. t.Error(err)
  154. } else if replicas[0] != 1 {
  155. t.Error("Incorrect (or unsorted) replica")
  156. } else if replicas[1] != 3 {
  157. t.Error("Incorrect (or unsorted) replica")
  158. } else if replicas[2] != 5 {
  159. t.Error("Incorrect (or unsorted) replica")
  160. }
  161. leader.Close()
  162. seedBroker.Close()
  163. safeClose(t, client)
  164. }
  165. func TestClientGetOffset(t *testing.T) {
  166. seedBroker := newMockBroker(t, 1)
  167. leader := newMockBroker(t, 2)
  168. leaderAddr := leader.Addr()
  169. metadata := new(MetadataResponse)
  170. metadata.AddTopicPartition("foo", 0, leader.BrokerID(), nil, nil, ErrNoError)
  171. metadata.AddBroker(leaderAddr, leader.BrokerID())
  172. seedBroker.Returns(metadata)
  173. client, err := NewClient([]string{seedBroker.Addr()}, nil)
  174. if err != nil {
  175. t.Fatal(err)
  176. }
  177. offsetResponse := new(OffsetResponse)
  178. offsetResponse.AddTopicPartition("foo", 0, 123)
  179. leader.Returns(offsetResponse)
  180. offset, err := client.GetOffset("foo", 0, OffsetNewest)
  181. if err != nil {
  182. t.Error(err)
  183. }
  184. if offset != 123 {
  185. t.Error("Unexpected offset, got ", offset)
  186. }
  187. leader.Close()
  188. seedBroker.Returns(metadata)
  189. leader = newMockBrokerAddr(t, 2, leaderAddr)
  190. offsetResponse = new(OffsetResponse)
  191. offsetResponse.AddTopicPartition("foo", 0, 456)
  192. leader.Returns(offsetResponse)
  193. offset, err = client.GetOffset("foo", 0, OffsetNewest)
  194. if err != nil {
  195. t.Error(err)
  196. }
  197. if offset != 456 {
  198. t.Error("Unexpected offset, got ", offset)
  199. }
  200. seedBroker.Close()
  201. leader.Close()
  202. safeClose(t, client)
  203. }
  204. func TestClientReceivingUnknownTopic(t *testing.T) {
  205. seedBroker := newMockBroker(t, 1)
  206. metadataResponse1 := new(MetadataResponse)
  207. seedBroker.Returns(metadataResponse1)
  208. config := NewConfig()
  209. config.Metadata.Retry.Max = 1
  210. config.Metadata.Retry.Backoff = 0
  211. client, err := NewClient([]string{seedBroker.Addr()}, config)
  212. if err != nil {
  213. t.Fatal(err)
  214. }
  215. metadataUnknownTopic := new(MetadataResponse)
  216. metadataUnknownTopic.AddTopic("new_topic", ErrUnknownTopicOrPartition)
  217. seedBroker.Returns(metadataUnknownTopic)
  218. seedBroker.Returns(metadataUnknownTopic)
  219. if err := client.RefreshMetadata("new_topic"); err != ErrUnknownTopicOrPartition {
  220. t.Error("ErrUnknownTopicOrPartition expected, got", err)
  221. }
  222. // If we are asking for the leader of a partition of the non-existing topic.
  223. // we will request metadata again.
  224. seedBroker.Returns(metadataUnknownTopic)
  225. seedBroker.Returns(metadataUnknownTopic)
  226. if _, err = client.Leader("new_topic", 1); err != ErrUnknownTopicOrPartition {
  227. t.Error("Expected ErrUnknownTopicOrPartition, got", err)
  228. }
  229. safeClose(t, client)
  230. seedBroker.Close()
  231. }
  232. func TestClientReceivingPartialMetadata(t *testing.T) {
  233. seedBroker := newMockBroker(t, 1)
  234. leader := newMockBroker(t, 5)
  235. metadataResponse1 := new(MetadataResponse)
  236. metadataResponse1.AddBroker(leader.Addr(), leader.BrokerID())
  237. seedBroker.Returns(metadataResponse1)
  238. config := NewConfig()
  239. config.Metadata.Retry.Max = 0
  240. client, err := NewClient([]string{seedBroker.Addr()}, config)
  241. if err != nil {
  242. t.Fatal(err)
  243. }
  244. replicas := []int32{leader.BrokerID(), seedBroker.BrokerID()}
  245. metadataPartial := new(MetadataResponse)
  246. metadataPartial.AddTopic("new_topic", ErrLeaderNotAvailable)
  247. metadataPartial.AddTopicPartition("new_topic", 0, leader.BrokerID(), replicas, replicas, ErrNoError)
  248. metadataPartial.AddTopicPartition("new_topic", 1, -1, replicas, []int32{}, ErrLeaderNotAvailable)
  249. seedBroker.Returns(metadataPartial)
  250. if err := client.RefreshMetadata("new_topic"); err != nil {
  251. t.Error("ErrLeaderNotAvailable should not make RefreshMetadata respond with an error")
  252. }
  253. // Even though the metadata was incomplete, we should be able to get the leader of a partition
  254. // for which we did get a useful response, without doing additional requests.
  255. partition0Leader, err := client.Leader("new_topic", 0)
  256. if err != nil {
  257. t.Error(err)
  258. } else if partition0Leader.Addr() != leader.Addr() {
  259. t.Error("Unexpected leader returned", partition0Leader.Addr())
  260. }
  261. // If we are asking for the leader of a partition that didn't have a leader before,
  262. // we will do another metadata request.
  263. seedBroker.Returns(metadataPartial)
  264. // Still no leader for the partition, so asking for it should return an error.
  265. _, err = client.Leader("new_topic", 1)
  266. if err != ErrLeaderNotAvailable {
  267. t.Error("Expected ErrLeaderNotAvailable, got", err)
  268. }
  269. safeClose(t, client)
  270. seedBroker.Close()
  271. leader.Close()
  272. }
  273. func TestClientRefreshBehaviour(t *testing.T) {
  274. seedBroker := newMockBroker(t, 1)
  275. leader := newMockBroker(t, 5)
  276. metadataResponse1 := new(MetadataResponse)
  277. metadataResponse1.AddBroker(leader.Addr(), leader.BrokerID())
  278. seedBroker.Returns(metadataResponse1)
  279. metadataResponse2 := new(MetadataResponse)
  280. metadataResponse2.AddTopicPartition("my_topic", 0xb, leader.BrokerID(), nil, nil, ErrNoError)
  281. seedBroker.Returns(metadataResponse2)
  282. client, err := NewClient([]string{seedBroker.Addr()}, nil)
  283. if err != nil {
  284. t.Fatal(err)
  285. }
  286. parts, err := client.Partitions("my_topic")
  287. if err != nil {
  288. t.Error(err)
  289. } else if len(parts) != 1 || parts[0] != 0xb {
  290. t.Error("Client returned incorrect partitions for my_topic:", parts)
  291. }
  292. tst, err := client.Leader("my_topic", 0xb)
  293. if err != nil {
  294. t.Error(err)
  295. } else if tst.ID() != 5 {
  296. t.Error("Leader for my_topic had incorrect ID.")
  297. }
  298. leader.Close()
  299. seedBroker.Close()
  300. safeClose(t, client)
  301. }
  302. func TestClientResurrectDeadSeeds(t *testing.T) {
  303. initialSeed := newMockBroker(t, 0)
  304. emptyMetadata := new(MetadataResponse)
  305. initialSeed.Returns(emptyMetadata)
  306. conf := NewConfig()
  307. conf.Metadata.Retry.Backoff = 0
  308. conf.Metadata.RefreshFrequency = 0
  309. c, err := NewClient([]string{initialSeed.Addr()}, conf)
  310. if err != nil {
  311. t.Fatal(err)
  312. }
  313. initialSeed.Close()
  314. client := c.(*client)
  315. seed1 := newMockBroker(t, 1)
  316. seed2 := newMockBroker(t, 2)
  317. seed3 := newMockBroker(t, 3)
  318. addr1 := seed1.Addr()
  319. addr2 := seed2.Addr()
  320. addr3 := seed3.Addr()
  321. // Overwrite the seed brokers with a fixed ordering to make this test deterministic.
  322. safeClose(t, client.seedBrokers[0])
  323. client.seedBrokers = []*Broker{NewBroker(addr1), NewBroker(addr2), NewBroker(addr3)}
  324. client.deadSeeds = []*Broker{}
  325. wg := sync.WaitGroup{}
  326. wg.Add(1)
  327. go func() {
  328. if err := client.RefreshMetadata(); err != nil {
  329. t.Error(err)
  330. }
  331. wg.Done()
  332. }()
  333. seed1.Close()
  334. seed2.Close()
  335. seed1 = newMockBrokerAddr(t, 1, addr1)
  336. seed2 = newMockBrokerAddr(t, 2, addr2)
  337. seed3.Close()
  338. seed1.Close()
  339. seed2.Returns(emptyMetadata)
  340. wg.Wait()
  341. if len(client.seedBrokers) != 2 {
  342. t.Error("incorrect number of live seeds")
  343. }
  344. if len(client.deadSeeds) != 1 {
  345. t.Error("incorrect number of dead seeds")
  346. }
  347. safeClose(t, c)
  348. }
  349. func TestClientCoordinatorWithConsumerOffsetsTopic(t *testing.T) {
  350. seedBroker := newMockBroker(t, 1)
  351. staleCoordinator := newMockBroker(t, 2)
  352. freshCoordinator := newMockBroker(t, 3)
  353. replicas := []int32{staleCoordinator.BrokerID(), freshCoordinator.BrokerID()}
  354. metadataResponse1 := new(MetadataResponse)
  355. metadataResponse1.AddBroker(staleCoordinator.Addr(), staleCoordinator.BrokerID())
  356. metadataResponse1.AddBroker(freshCoordinator.Addr(), freshCoordinator.BrokerID())
  357. metadataResponse1.AddTopicPartition("__consumer_offsets", 0, replicas[0], replicas, replicas, ErrNoError)
  358. seedBroker.Returns(metadataResponse1)
  359. client, err := NewClient([]string{seedBroker.Addr()}, nil)
  360. if err != nil {
  361. t.Fatal(err)
  362. }
  363. coordinatorResponse1 := new(ConsumerMetadataResponse)
  364. coordinatorResponse1.Err = ErrConsumerCoordinatorNotAvailable
  365. seedBroker.Returns(coordinatorResponse1)
  366. coordinatorResponse2 := new(ConsumerMetadataResponse)
  367. coordinatorResponse2.CoordinatorID = staleCoordinator.BrokerID()
  368. coordinatorResponse2.CoordinatorHost = "127.0.0.1"
  369. coordinatorResponse2.CoordinatorPort = staleCoordinator.Port()
  370. seedBroker.Returns(coordinatorResponse2)
  371. broker, err := client.Coordinator("my_group")
  372. if err != nil {
  373. t.Error(err)
  374. }
  375. if staleCoordinator.Addr() != broker.Addr() {
  376. t.Errorf("Expected coordinator to have address %s, found %s", staleCoordinator.Addr(), broker.Addr())
  377. }
  378. if staleCoordinator.BrokerID() != broker.ID() {
  379. t.Errorf("Expected coordinator to have ID %d, found %d", staleCoordinator.BrokerID(), broker.ID())
  380. }
  381. // Grab the cached value
  382. broker2, err := client.Coordinator("my_group")
  383. if err != nil {
  384. t.Error(err)
  385. }
  386. if broker2.Addr() != broker.Addr() {
  387. t.Errorf("Expected the coordinator to be the same, but found %s vs. %s", broker2.Addr(), broker.Addr())
  388. }
  389. coordinatorResponse3 := new(ConsumerMetadataResponse)
  390. coordinatorResponse3.CoordinatorID = freshCoordinator.BrokerID()
  391. coordinatorResponse3.CoordinatorHost = "127.0.0.1"
  392. coordinatorResponse3.CoordinatorPort = freshCoordinator.Port()
  393. seedBroker.Returns(coordinatorResponse3)
  394. // Refresh the locally cahced value because it's stale
  395. if err := client.RefreshCoordinator("my_group"); err != nil {
  396. t.Error(err)
  397. }
  398. // Grab the fresh value
  399. broker3, err := client.Coordinator("my_group")
  400. if err != nil {
  401. t.Error(err)
  402. }
  403. if broker3.Addr() != freshCoordinator.Addr() {
  404. t.Errorf("Expected the freshCoordinator to be returned, but found %s.", broker3.Addr())
  405. }
  406. freshCoordinator.Close()
  407. staleCoordinator.Close()
  408. seedBroker.Close()
  409. safeClose(t, client)
  410. }
  411. func TestClientCoordinatorWithoutConsumerOffsetsTopic(t *testing.T) {
  412. seedBroker := newMockBroker(t, 1)
  413. coordinator := newMockBroker(t, 2)
  414. metadataResponse1 := new(MetadataResponse)
  415. seedBroker.Returns(metadataResponse1)
  416. config := NewConfig()
  417. config.Metadata.Retry.Max = 1
  418. config.Metadata.Retry.Backoff = 0
  419. client, err := NewClient([]string{seedBroker.Addr()}, config)
  420. if err != nil {
  421. t.Fatal(err)
  422. }
  423. coordinatorResponse1 := new(ConsumerMetadataResponse)
  424. coordinatorResponse1.Err = ErrConsumerCoordinatorNotAvailable
  425. seedBroker.Returns(coordinatorResponse1)
  426. metadataResponse2 := new(MetadataResponse)
  427. metadataResponse2.AddTopic("__consumer_offsets", ErrUnknownTopicOrPartition)
  428. seedBroker.Returns(metadataResponse2)
  429. replicas := []int32{coordinator.BrokerID()}
  430. metadataResponse3 := new(MetadataResponse)
  431. metadataResponse3.AddTopicPartition("__consumer_offsets", 0, replicas[0], replicas, replicas, ErrNoError)
  432. seedBroker.Returns(metadataResponse3)
  433. coordinatorResponse2 := new(ConsumerMetadataResponse)
  434. coordinatorResponse2.CoordinatorID = coordinator.BrokerID()
  435. coordinatorResponse2.CoordinatorHost = "127.0.0.1"
  436. coordinatorResponse2.CoordinatorPort = coordinator.Port()
  437. seedBroker.Returns(coordinatorResponse2)
  438. broker, err := client.Coordinator("my_group")
  439. if err != nil {
  440. t.Error(err)
  441. }
  442. if coordinator.Addr() != broker.Addr() {
  443. t.Errorf("Expected coordinator to have address %s, found %s", coordinator.Addr(), broker.Addr())
  444. }
  445. if coordinator.BrokerID() != broker.ID() {
  446. t.Errorf("Expected coordinator to have ID %d, found %d", coordinator.BrokerID(), broker.ID())
  447. }
  448. coordinator.Close()
  449. seedBroker.Close()
  450. safeClose(t, client)
  451. }
  452. func TestClientAutorefreshShutdownRace(t *testing.T) {
  453. seedBroker := newMockBroker(t, 1)
  454. metadataResponse := new(MetadataResponse)
  455. seedBroker.Returns(metadataResponse)
  456. conf := NewConfig()
  457. conf.Metadata.RefreshFrequency = 100 * time.Millisecond
  458. client, err := NewClient([]string{seedBroker.Addr()}, conf)
  459. if err != nil {
  460. t.Fatal(err)
  461. }
  462. // Wait for the background refresh to kick in
  463. time.Sleep(110 * time.Millisecond)
  464. done := make(chan none)
  465. go func() {
  466. // Close the client
  467. if err := client.Close(); err != nil {
  468. t.Fatal(err)
  469. }
  470. close(done)
  471. }()
  472. // Wait for the Close to kick in
  473. time.Sleep(10 * time.Millisecond)
  474. // Then return some metadata to the still-running background thread
  475. leader := newMockBroker(t, 2)
  476. metadataResponse.AddBroker(leader.Addr(), leader.BrokerID())
  477. metadataResponse.AddTopicPartition("foo", 0, leader.BrokerID(), []int32{2}, []int32{2}, ErrNoError)
  478. seedBroker.Returns(metadataResponse)
  479. <-done
  480. seedBroker.Close()
  481. // give the update time to happen so we get a panic if it's still running (which it shouldn't)
  482. time.Sleep(10 * time.Millisecond)
  483. }