client_test.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611
  1. // Copyright 2012-2015 Oliver Eilhard. All rights reserved.
  2. // Use of this source code is governed by a MIT-license.
  3. // See http://olivere.mit-license.org/license.txt for details.
  4. package elastic
  5. import (
  6. "bytes"
  7. "encoding/json"
  8. "log"
  9. "net/http"
  10. "regexp"
  11. "strings"
  12. "testing"
  13. "time"
  14. )
  15. func findConn(s string, slice ...*conn) (int, bool) {
  16. for i, t := range slice {
  17. if s == t.URL() {
  18. return i, true
  19. }
  20. }
  21. return -1, false
  22. }
  23. // -- NewClient --
  24. func TestClientDefaults(t *testing.T) {
  25. client, err := NewClient()
  26. if err != nil {
  27. t.Fatal(err)
  28. }
  29. if client.healthcheckEnabled != true {
  30. t.Errorf("expected health checks to be enabled, got: %v", client.healthcheckEnabled)
  31. }
  32. if client.healthcheckTimeoutStartup != DefaultHealthcheckTimeoutStartup {
  33. t.Errorf("expected health checks timeout on startup = %v, got: %v", DefaultHealthcheckTimeoutStartup, client.healthcheckTimeoutStartup)
  34. }
  35. if client.healthcheckTimeout != DefaultHealthcheckTimeout {
  36. t.Errorf("expected health checks timeout = %v, got: %v", DefaultHealthcheckTimeout, client.healthcheckTimeout)
  37. }
  38. if client.healthcheckInterval != DefaultHealthcheckInterval {
  39. t.Errorf("expected health checks interval = %v, got: %v", DefaultHealthcheckInterval, client.healthcheckInterval)
  40. }
  41. if client.snifferEnabled != true {
  42. t.Errorf("expected sniffing to be enabled, got: %v", client.snifferEnabled)
  43. }
  44. if client.snifferTimeoutStartup != DefaultSnifferTimeoutStartup {
  45. t.Errorf("expected sniffer timeout on startup = %v, got: %v", DefaultSnifferTimeoutStartup, client.snifferTimeoutStartup)
  46. }
  47. if client.snifferTimeout != DefaultSnifferTimeout {
  48. t.Errorf("expected sniffer timeout = %v, got: %v", DefaultSnifferTimeout, client.snifferTimeout)
  49. }
  50. if client.snifferInterval != DefaultSnifferInterval {
  51. t.Errorf("expected sniffer interval = %v, got: %v", DefaultSnifferInterval, client.snifferInterval)
  52. }
  53. }
  54. func TestClientWithoutURL(t *testing.T) {
  55. client, err := NewClient()
  56. if err != nil {
  57. t.Fatal(err)
  58. }
  59. // Two things should happen here:
  60. // 1. The client starts sniffing the cluster on DefaultURL
  61. // 2. The sniffing process should find (at least) one node in the cluster, i.e. the DefaultURL
  62. if len(client.conns) == 0 {
  63. t.Fatalf("expected at least 1 node in the cluster, got: %d (%v)", len(client.conns), client.conns)
  64. }
  65. if !isTravis() {
  66. if _, found := findConn(DefaultURL, client.conns...); !found {
  67. t.Errorf("expected to find node with default URL of %s in %v", DefaultURL, client.conns)
  68. }
  69. }
  70. }
  71. func TestClientWithSingleURL(t *testing.T) {
  72. client, err := NewClient(SetURL("http://localhost:9200"))
  73. if err != nil {
  74. t.Fatal(err)
  75. }
  76. // Two things should happen here:
  77. // 1. The client starts sniffing the cluster on DefaultURL
  78. // 2. The sniffing process should find (at least) one node in the cluster, i.e. the DefaultURL
  79. if len(client.conns) == 0 {
  80. t.Fatalf("expected at least 1 node in the cluster, got: %d (%v)", len(client.conns), client.conns)
  81. }
  82. if !isTravis() {
  83. if _, found := findConn(DefaultURL, client.conns...); !found {
  84. t.Errorf("expected to find node with default URL of %s in %v", DefaultURL, client.conns)
  85. }
  86. }
  87. }
  88. func TestClientWithMultipleURLs(t *testing.T) {
  89. client, err := NewClient(SetURL("http://localhost:9200", "http://localhost:9201"))
  90. if err != nil {
  91. t.Fatal(err)
  92. }
  93. // The client should sniff both URLs, but only localhost:9200 should return nodes.
  94. if len(client.conns) != 1 {
  95. t.Fatalf("expected exactly 1 node in the local cluster, got: %d (%v)", len(client.conns), client.conns)
  96. }
  97. if !isTravis() {
  98. if client.conns[0].URL() != DefaultURL {
  99. t.Errorf("expected to find node with default URL of %s in %v", DefaultURL, client.conns)
  100. }
  101. }
  102. }
  103. func TestClientSniffSuccess(t *testing.T) {
  104. client, err := NewClient(SetURL("http://localhost:19200", "http://localhost:9200"))
  105. if err != nil {
  106. t.Fatal(err)
  107. }
  108. // The client should sniff both URLs, but only localhost:9200 should return nodes.
  109. if len(client.conns) != 1 {
  110. t.Fatalf("expected exactly 1 node in the local cluster, got: %d (%v)", len(client.conns), client.conns)
  111. }
  112. }
  113. func TestClientSniffFailure(t *testing.T) {
  114. _, err := NewClient(SetURL("http://localhost:19200", "http://localhost:19201"))
  115. if err == nil {
  116. t.Fatalf("expected cluster to fail with no nodes found")
  117. }
  118. }
  119. func TestClientSniffDisabled(t *testing.T) {
  120. client, err := NewClient(SetSniff(false), SetURL("http://localhost:9200", "http://localhost:9201"))
  121. if err != nil {
  122. t.Fatal(err)
  123. }
  124. // The client should not sniff, so it should have two connections.
  125. if len(client.conns) != 2 {
  126. t.Fatalf("expected 2 nodes, got: %d (%v)", len(client.conns), client.conns)
  127. }
  128. // Make two requests, so that both connections are being used
  129. for i := 0; i < len(client.conns); i++ {
  130. _, err = client.Flush().Do()
  131. if err != nil {
  132. t.Fatal(err)
  133. }
  134. }
  135. // The first connection (localhost:9200) should now be okay.
  136. if i, found := findConn("http://localhost:9200", client.conns...); !found {
  137. t.Fatalf("expected connection to %q to be found", "http://localhost:9200")
  138. } else {
  139. if conn := client.conns[i]; conn.IsDead() {
  140. t.Fatal("expected connection to be alive, but it is dead")
  141. }
  142. }
  143. // The second connection (localhost:9201) should now be marked as dead.
  144. if i, found := findConn("http://localhost:9201", client.conns...); !found {
  145. t.Fatalf("expected connection to %q to be found", "http://localhost:9201")
  146. } else {
  147. if conn := client.conns[i]; !conn.IsDead() {
  148. t.Fatal("expected connection to be dead, but it is alive")
  149. }
  150. }
  151. }
  152. // -- Start and stop --
  153. func TestClientStartAndStop(t *testing.T) {
  154. client, err := NewClient()
  155. if err != nil {
  156. t.Fatal(err)
  157. }
  158. running := client.IsRunning()
  159. if !running {
  160. t.Fatalf("expected background processes to run; got: %v", running)
  161. }
  162. // Stop
  163. client.Stop()
  164. running = client.IsRunning()
  165. if running {
  166. t.Fatalf("expected background processes to be stopped; got: %v", running)
  167. }
  168. // Stop again => no-op
  169. client.Stop()
  170. running = client.IsRunning()
  171. if running {
  172. t.Fatalf("expected background processes to be stopped; got: %v", running)
  173. }
  174. // Start
  175. client.Start()
  176. running = client.IsRunning()
  177. if !running {
  178. t.Fatalf("expected background processes to run; got: %v", running)
  179. }
  180. // Start again => no-op
  181. client.Start()
  182. running = client.IsRunning()
  183. if !running {
  184. t.Fatalf("expected background processes to run; got: %v", running)
  185. }
  186. }
  187. // -- Sniffing --
  188. func TestClientSniffNode(t *testing.T) {
  189. client, err := NewClient()
  190. if err != nil {
  191. t.Fatal(err)
  192. }
  193. ch := make(chan []*conn)
  194. go func() { ch <- client.sniffNode(DefaultURL) }()
  195. select {
  196. case nodes := <-ch:
  197. if len(nodes) != 1 {
  198. t.Fatalf("expected %d nodes; got: %d", 1, len(nodes))
  199. }
  200. pattern := `http:\/\/[\d\.]+:9200`
  201. matched, err := regexp.MatchString(pattern, nodes[0].URL())
  202. if err != nil {
  203. t.Fatal(err)
  204. }
  205. if !matched {
  206. t.Fatalf("expected node URL pattern %q; got: %q", pattern, nodes[0].URL())
  207. }
  208. case <-time.After(2 * time.Second):
  209. t.Fatal("expected no timeout in sniff node")
  210. break
  211. }
  212. }
  213. func TestClientSniffOnDefaultURL(t *testing.T) {
  214. client, _ := NewClient()
  215. if client == nil {
  216. t.Fatal("no client returned")
  217. }
  218. ch := make(chan error, 1)
  219. go func() {
  220. ch <- client.sniff(DefaultSnifferTimeoutStartup)
  221. }()
  222. select {
  223. case err := <-ch:
  224. if err != nil {
  225. t.Fatalf("expected sniff to succeed; got: %v", err)
  226. }
  227. if len(client.conns) != 1 {
  228. t.Fatalf("expected %d nodes; got: %d", 1, len(client.conns))
  229. }
  230. pattern := `http:\/\/[\d\.]+:9200`
  231. matched, err := regexp.MatchString(pattern, client.conns[0].URL())
  232. if err != nil {
  233. t.Fatal(err)
  234. }
  235. if !matched {
  236. t.Fatalf("expected node URL pattern %q; got: %q", pattern, client.conns[0].URL())
  237. }
  238. case <-time.After(2 * time.Second):
  239. t.Fatal("expected no timeout in sniff")
  240. break
  241. }
  242. }
  243. // -- Selector --
  244. func TestClientSelectConnHealthy(t *testing.T) {
  245. client, err := NewClient(
  246. SetSniff(false),
  247. SetHealthcheck(false),
  248. SetURL("http://127.0.0.1:9200", "http://127.0.0.1:9201"))
  249. if err != nil {
  250. t.Fatal(err)
  251. }
  252. // Both are healthy, so we should get both URLs in round-robin
  253. client.conns[0].MarkAsHealthy()
  254. client.conns[1].MarkAsHealthy()
  255. // #1: Return 1st
  256. c, err := client.next()
  257. if err != nil {
  258. t.Fatal(err)
  259. }
  260. if c.URL() != client.conns[0].URL() {
  261. t.Fatalf("expected %s; got: %s", c.URL(), client.conns[0].URL())
  262. }
  263. // #2: Return 2nd
  264. c, err = client.next()
  265. if err != nil {
  266. t.Fatal(err)
  267. }
  268. if c.URL() != client.conns[1].URL() {
  269. t.Fatalf("expected %s; got: %s", c.URL(), client.conns[1].URL())
  270. }
  271. // #3: Return 1st
  272. c, err = client.next()
  273. if err != nil {
  274. t.Fatal(err)
  275. }
  276. if c.URL() != client.conns[0].URL() {
  277. t.Fatalf("expected %s; got: %s", c.URL(), client.conns[0].URL())
  278. }
  279. }
  280. func TestClientSelectConnHealthyAndDead(t *testing.T) {
  281. client, err := NewClient(
  282. SetSniff(false),
  283. SetHealthcheck(false),
  284. SetURL("http://127.0.0.1:9200", "http://127.0.0.1:9201"))
  285. if err != nil {
  286. t.Fatal(err)
  287. }
  288. // 1st is healthy, second is dead
  289. client.conns[0].MarkAsHealthy()
  290. client.conns[1].MarkAsDead()
  291. // #1: Return 1st
  292. c, err := client.next()
  293. if err != nil {
  294. t.Fatal(err)
  295. }
  296. if c.URL() != client.conns[0].URL() {
  297. t.Fatalf("expected %s; got: %s", c.URL(), client.conns[0].URL())
  298. }
  299. // #2: Return 1st again
  300. c, err = client.next()
  301. if err != nil {
  302. t.Fatal(err)
  303. }
  304. if c.URL() != client.conns[0].URL() {
  305. t.Fatalf("expected %s; got: %s", c.URL(), client.conns[0].URL())
  306. }
  307. // #3: Return 1st again and again
  308. c, err = client.next()
  309. if err != nil {
  310. t.Fatal(err)
  311. }
  312. if c.URL() != client.conns[0].URL() {
  313. t.Fatalf("expected %s; got: %s", c.URL(), client.conns[0].URL())
  314. }
  315. }
  316. func TestClientSelectConnDeadAndHealthy(t *testing.T) {
  317. client, err := NewClient(
  318. SetSniff(false),
  319. SetHealthcheck(false),
  320. SetURL("http://127.0.0.1:9200", "http://127.0.0.1:9201"))
  321. if err != nil {
  322. t.Fatal(err)
  323. }
  324. // 1st is dead, 2nd is healthy
  325. client.conns[0].MarkAsDead()
  326. client.conns[1].MarkAsHealthy()
  327. // #1: Return 2nd
  328. c, err := client.next()
  329. if err != nil {
  330. t.Fatal(err)
  331. }
  332. if c.URL() != client.conns[1].URL() {
  333. t.Fatalf("expected %s; got: %s", c.URL(), client.conns[1].URL())
  334. }
  335. // #2: Return 2nd again
  336. c, err = client.next()
  337. if err != nil {
  338. t.Fatal(err)
  339. }
  340. if c.URL() != client.conns[1].URL() {
  341. t.Fatalf("expected %s; got: %s", c.URL(), client.conns[1].URL())
  342. }
  343. // #3: Return 2nd again and again
  344. c, err = client.next()
  345. if err != nil {
  346. t.Fatal(err)
  347. }
  348. if c.URL() != client.conns[1].URL() {
  349. t.Fatalf("expected %s; got: %s", c.URL(), client.conns[1].URL())
  350. }
  351. }
  352. func TestClientSelectConnAllDead(t *testing.T) {
  353. client, err := NewClient(
  354. SetSniff(false),
  355. SetHealthcheck(false),
  356. SetURL("http://127.0.0.1:9200", "http://127.0.0.1:9201"))
  357. if err != nil {
  358. t.Fatal(err)
  359. }
  360. // Both are dead
  361. client.conns[0].MarkAsDead()
  362. client.conns[1].MarkAsDead()
  363. // #1: Return ErrNoClient
  364. c, err := client.next()
  365. if err != ErrNoClient {
  366. t.Fatal(err)
  367. }
  368. if c != nil {
  369. t.Fatalf("expected no connection; got: %v", c)
  370. }
  371. // #2: Return ErrNoClient again
  372. c, err = client.next()
  373. if err != ErrNoClient {
  374. t.Fatal(err)
  375. }
  376. if c != nil {
  377. t.Fatalf("expected no connection; got: %v", c)
  378. }
  379. // #3: Return ErrNoClient again and again
  380. c, err = client.next()
  381. if err != ErrNoClient {
  382. t.Fatal(err)
  383. }
  384. if c != nil {
  385. t.Fatalf("expected no connection; got: %v", c)
  386. }
  387. }
  388. // -- ElasticsearchVersion --
  389. func TestElasticsearchVersion(t *testing.T) {
  390. client, err := NewClient()
  391. if err != nil {
  392. t.Fatal(err)
  393. }
  394. version, err := client.ElasticsearchVersion(DefaultURL)
  395. if err != nil {
  396. t.Fatal(err)
  397. }
  398. if version == "" {
  399. t.Errorf("expected a version number, got: %q", version)
  400. }
  401. }
  402. // -- IndexNames --
  403. func TestIndexNames(t *testing.T) {
  404. client := setupTestClientAndCreateIndex(t)
  405. names, err := client.IndexNames()
  406. if err != nil {
  407. t.Fatal(err)
  408. }
  409. if len(names) == 0 {
  410. t.Fatalf("expected some index names, got: %d", len(names))
  411. }
  412. var found bool
  413. for _, name := range names {
  414. if name == testIndexName {
  415. found = true
  416. break
  417. }
  418. }
  419. if !found {
  420. t.Fatalf("expected to find index %q; got: %v", testIndexName, found)
  421. }
  422. }
  423. // -- PerformRequest --
  424. func TestPerformRequest(t *testing.T) {
  425. client, err := NewClient()
  426. if err != nil {
  427. t.Fatal(err)
  428. }
  429. res, err := client.PerformRequest("GET", "/", nil, nil)
  430. if err != nil {
  431. t.Fatal(err)
  432. }
  433. if res == nil {
  434. t.Fatal("expected response to be != nil")
  435. }
  436. ret := new(PingResult)
  437. if err := json.Unmarshal(res.Body, ret); err != nil {
  438. t.Fatalf("expected no error on decode; got: %v", err)
  439. }
  440. if ret.Status != 200 {
  441. t.Errorf("expected HTTP status 200; got: %d", ret.Status)
  442. }
  443. }
  444. func TestPerformRequestWithLogger(t *testing.T) {
  445. var w bytes.Buffer
  446. out := log.New(&w, "LOGGER ", log.LstdFlags)
  447. client, err := NewClient(SetInfoLog(out))
  448. if err != nil {
  449. t.Fatal(err)
  450. }
  451. res, err := client.PerformRequest("GET", "/", nil, nil)
  452. if err != nil {
  453. t.Fatal(err)
  454. }
  455. if res == nil {
  456. t.Fatal("expected response to be != nil")
  457. }
  458. ret := new(PingResult)
  459. if err := json.Unmarshal(res.Body, ret); err != nil {
  460. t.Fatalf("expected no error on decode; got: %v", err)
  461. }
  462. if ret.Status != 200 {
  463. t.Errorf("expected HTTP status 200; got: %d", ret.Status)
  464. }
  465. got := w.String()
  466. pattern := `^LOGGER \d{4}/\d{2}/\d{2} \d{2}:\d{2}:\d{2} GET http://.*/ \[status:200, request:\d+\.\d{3}s\]\n`
  467. matched, err := regexp.MatchString(pattern, got)
  468. if err != nil {
  469. t.Fatalf("expected log line to match %q; got: %v", pattern, err)
  470. }
  471. if !matched {
  472. t.Errorf("expected log line to match %q; got: %v", pattern, got)
  473. }
  474. }
  475. func TestPerformRequestWithLoggerAndTracer(t *testing.T) {
  476. var lw bytes.Buffer
  477. lout := log.New(&lw, "LOGGER ", log.LstdFlags)
  478. var tw bytes.Buffer
  479. tout := log.New(&tw, "TRACER ", log.LstdFlags)
  480. client, err := NewClient(SetInfoLog(lout), SetTraceLog(tout))
  481. if err != nil {
  482. t.Fatal(err)
  483. }
  484. res, err := client.PerformRequest("GET", "/", nil, nil)
  485. if err != nil {
  486. t.Fatal(err)
  487. }
  488. if res == nil {
  489. t.Fatal("expected response to be != nil")
  490. }
  491. ret := new(PingResult)
  492. if err := json.Unmarshal(res.Body, ret); err != nil {
  493. t.Fatalf("expected no error on decode; got: %v", err)
  494. }
  495. if ret.Status != 200 {
  496. t.Errorf("expected HTTP status 200; got: %d", ret.Status)
  497. }
  498. lgot := lw.String()
  499. if lgot == "" {
  500. t.Errorf("expected logger output; got: %q", lgot)
  501. }
  502. tgot := tw.String()
  503. if tgot == "" {
  504. t.Errorf("expected tracer output; got: %q", tgot)
  505. }
  506. }
  507. // failingTransport will run a fail callback if it sees a given URL path prefix.
  508. type failingTransport struct {
  509. path string // path prefix to look for
  510. fail func(*http.Request) (*http.Response, error) // call when path prefix is found
  511. next http.RoundTripper // next round-tripper (use http.DefaultTransport if nil)
  512. }
  513. // RoundTrip implements a failing transport.
  514. func (tr *failingTransport) RoundTrip(r *http.Request) (*http.Response, error) {
  515. if strings.HasPrefix(r.URL.Path, tr.path) && tr.fail != nil {
  516. return tr.fail(r)
  517. }
  518. if tr.next != nil {
  519. return tr.next.RoundTrip(r)
  520. }
  521. return http.DefaultTransport.RoundTrip(r)
  522. }
  523. func TestPerformRequestWithMaxRetries(t *testing.T) {
  524. var numFailedReqs int
  525. fail := func(r *http.Request) (*http.Response, error) {
  526. numFailedReqs += 1
  527. return &http.Response{Request: r, StatusCode: 400}, nil
  528. }
  529. // Run against a failing endpoint and see if PerformRequest
  530. // retries correctly.
  531. tr := &failingTransport{path: "/fail", fail: fail}
  532. httpClient := &http.Client{Transport: tr}
  533. client, err := NewClient(SetHttpClient(httpClient), SetMaxRetries(5))
  534. if err != nil {
  535. t.Fatal(err)
  536. }
  537. res, err := client.PerformRequest("GET", "/fail", nil, nil)
  538. if err == nil {
  539. t.Fatal("expected error")
  540. }
  541. if res != nil {
  542. t.Fatal("expected no response")
  543. }
  544. // Connection should be marked as dead after it failed
  545. if numFailedReqs != 5 {
  546. t.Errorf("expected %d failed requests; got: %d", 5, numFailedReqs)
  547. }
  548. }