You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

EsTester.java 8.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. /*
  2. * SonarQube, open source software quality management tool.
  3. * Copyright (C) 2008-2014 SonarSource
  4. * mailto:contact AT sonarsource DOT com
  5. *
  6. * SonarQube is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU Lesser General Public
  8. * License as published by the Free Software Foundation; either
  9. * version 3 of the License, or (at your option) any later version.
  10. *
  11. * SonarQube is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. * Lesser General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Lesser General Public License
  17. * along with this program; if not, write to the Free Software Foundation,
  18. * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  19. */
  20. package org.sonar.server.es;
  21. import com.google.common.base.Function;
  22. import com.google.common.base.Throwables;
  23. import com.google.common.collect.Collections2;
  24. import com.google.common.collect.Iterables;
  25. import org.apache.commons.io.IOUtils;
  26. import org.apache.commons.lang.math.RandomUtils;
  27. import org.apache.commons.lang.reflect.ConstructorUtils;
  28. import org.elasticsearch.action.admin.indices.delete.DeleteIndexResponse;
  29. import org.elasticsearch.action.bulk.BulkRequestBuilder;
  30. import org.elasticsearch.action.index.IndexRequest;
  31. import org.elasticsearch.action.search.SearchRequestBuilder;
  32. import org.elasticsearch.action.search.SearchResponse;
  33. import org.elasticsearch.action.search.SearchType;
  34. import org.elasticsearch.cluster.metadata.IndexMetaData;
  35. import org.elasticsearch.cluster.node.DiscoveryNode;
  36. import org.elasticsearch.common.settings.ImmutableSettings;
  37. import org.elasticsearch.common.unit.TimeValue;
  38. import org.elasticsearch.index.query.QueryBuilders;
  39. import org.elasticsearch.node.Node;
  40. import org.elasticsearch.node.NodeBuilder;
  41. import org.elasticsearch.search.SearchHit;
  42. import org.junit.rules.ExternalResource;
  43. import org.sonar.core.platform.ComponentContainer;
  44. import org.sonar.server.search.BaseDoc;
  45. import org.sonar.test.TestUtils;
  46. import java.io.File;
  47. import java.io.FileInputStream;
  48. import java.util.Collections;
  49. import java.util.List;
  50. import java.util.Map;
  51. import static com.google.common.collect.Lists.newArrayList;
  52. import static org.assertj.core.api.Assertions.assertThat;
  53. public class EsTester extends ExternalResource {
  54. private static final int INSTANCE_ID = RandomUtils.nextInt();
  55. private Node node;
  56. private EsClient client;
  57. private final List<IndexDefinition> definitions = newArrayList();
  58. public EsTester addDefinitions(IndexDefinition... defs) {
  59. Collections.addAll(definitions, defs);
  60. return this;
  61. }
  62. protected void before() throws Throwable {
  63. String nodeName = "tmp-es-" + INSTANCE_ID;
  64. node = NodeBuilder.nodeBuilder().local(true).data(true).settings(ImmutableSettings.builder()
  65. .put("cluster.name", nodeName)
  66. .put("node.name", nodeName)
  67. // the two following properties are probably not used because they are
  68. // declared on indices too
  69. .put(IndexMetaData.SETTING_NUMBER_OF_SHARDS, 1)
  70. .put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, 0)
  71. // limit the number of threads created (see org.elasticsearch.common.util.concurrent.EsExecutors)
  72. .put("processors", 1)
  73. .put("http.enabled", false)
  74. .put("index.store.type", "mmapfs")
  75. .put("config.ignore_system_properties", true)
  76. // reuse the same directory than other tests for faster initialization
  77. .put("path.home", "target/" + nodeName)
  78. .put("gateway.type", "none"))
  79. .build();
  80. node.start();
  81. assertThat(DiscoveryNode.localNode(node.settings())).isTrue();
  82. // wait for node to be ready
  83. node.client().admin().cluster().prepareHealth()
  84. .setWaitForGreenStatus()
  85. .get();
  86. // delete the indices created by previous tests
  87. DeleteIndexResponse response = node.client().admin().indices().prepareDelete("_all").get();
  88. assertThat(response.isAcknowledged()).isTrue();
  89. client = new EsClient(node.client());
  90. client.start();
  91. if (!definitions.isEmpty()) {
  92. ComponentContainer container = new ComponentContainer();
  93. container.addSingletons(definitions);
  94. container.addSingleton(client);
  95. container.addSingleton(IndexDefinitions.class);
  96. container.addSingleton(IndexCreator.class);
  97. container.startComponents();
  98. }
  99. }
  100. @Override
  101. protected void after() {
  102. if (client != null) {
  103. client.stop();
  104. }
  105. if (node != null) {
  106. node.stop();
  107. node.close();
  108. }
  109. }
  110. public void truncateIndices() {
  111. client.prepareDeleteByQuery(client.prepareState().get()
  112. .getState().getMetaData().concreteAllIndices())
  113. .setQuery(QueryBuilders.matchAllQuery())
  114. .get();
  115. client.prepareRefresh(client.prepareState().get()
  116. .getState().getMetaData().concreteAllIndices())
  117. .setForce(true)
  118. .get();
  119. client.prepareFlush(client.prepareState().get()
  120. .getState().getMetaData().concreteAllIndices())
  121. .get();
  122. }
  123. public void putDocuments(String index, String type, Class<?> testClass, String... jsonPaths) throws Exception {
  124. BulkRequestBuilder bulk = client.prepareBulk().setRefresh(true);
  125. for (String path : jsonPaths) {
  126. File file = TestUtils.getResource(testClass, path);
  127. if (file == null) {
  128. throw new IllegalArgumentException(String.format("File '%s' hasn't been found in folder '%s'", path, testClass.getSimpleName()));
  129. }
  130. bulk.add(new IndexRequest(index, type).source(IOUtils.toString(new FileInputStream(file))));
  131. }
  132. bulk.get();
  133. }
  134. public void putDocuments(String index, String type, BaseDoc... docs) throws Exception {
  135. BulkRequestBuilder bulk = client.prepareBulk().setRefresh(true);
  136. for (BaseDoc doc : docs) {
  137. bulk.add(new IndexRequest(index, type).source(doc.getFields()));
  138. }
  139. bulk.get();
  140. }
  141. public void putDocuments(String index, String type, Map<String, Object>... docs) throws Exception {
  142. BulkRequestBuilder bulk = client.prepareBulk().setRefresh(true);
  143. for (Map<String, Object> doc : docs) {
  144. bulk.add(new IndexRequest(index, type).source(doc));
  145. }
  146. bulk.get();
  147. }
  148. public long countDocuments(String indexName, String typeName) {
  149. return client().prepareCount(indexName).setTypes(typeName).get().getCount();
  150. }
  151. /**
  152. * Get all the indexed documents (no paginated results). Results are converted to BaseDoc objects.
  153. * Results are not sorted.
  154. */
  155. public <E extends BaseDoc> List<E> getDocuments(String indexName, String typeName, final Class<E> docClass) {
  156. List<SearchHit> hits = getDocuments(indexName, typeName);
  157. return newArrayList(Collections2.transform(hits, new Function<SearchHit, E>() {
  158. @Override
  159. public E apply(SearchHit input) {
  160. try {
  161. return (E) ConstructorUtils.invokeConstructor(docClass, input.getSource());
  162. } catch (Exception e) {
  163. throw Throwables.propagate(e);
  164. }
  165. }
  166. }));
  167. }
  168. /**
  169. * Get all the indexed documents (no paginated results). Results are not sorted.
  170. */
  171. public List<SearchHit> getDocuments(String indexName, String typeName) {
  172. SearchRequestBuilder req = client.nativeClient().prepareSearch(indexName).setTypes(typeName).setQuery(QueryBuilders.matchAllQuery());
  173. req.setSearchType(SearchType.SCAN)
  174. .setScroll(new TimeValue(60000))
  175. .setSize(100);
  176. SearchResponse response = req.get();
  177. List<SearchHit> result = newArrayList();
  178. while (true) {
  179. Iterables.addAll(result, response.getHits());
  180. response = client.nativeClient().prepareSearchScroll(response.getScrollId()).setScroll(new TimeValue(600000)).execute().actionGet();
  181. // Break condition: No hits are returned
  182. if (response.getHits().getHits().length == 0) {
  183. break;
  184. }
  185. }
  186. return result;
  187. }
  188. /**
  189. * Get a list of a specific field from all indexed documents.
  190. */
  191. public <T> List<T> getDocumentFieldValues(String indexName, String typeName, final String fieldNameToReturn) {
  192. return newArrayList(Iterables.transform(getDocuments(indexName, typeName), new Function<SearchHit, T>() {
  193. @Override
  194. public T apply(SearchHit input) {
  195. return (T) input.sourceAsMap().get(fieldNameToReturn);
  196. }
  197. }));
  198. }
  199. public Node node() {
  200. return node;
  201. }
  202. public EsClient client() {
  203. return client;
  204. }
  205. }