MetaDataIndexStateService.java 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. /*
  2. * Licensed to ElasticSearch and Shay Banon under one
  3. * or more contributor license agreements. See the NOTICE file
  4. * distributed with this work for additional information
  5. * regarding copyright ownership. ElasticSearch licenses this
  6. * file to you under the Apache License, Version 2.0 (the
  7. * "License"); you may not use this file except in compliance
  8. * with the License. You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing,
  13. * software distributed under the License is distributed on an
  14. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15. * KIND, either express or implied. See the License for the
  16. * specific language governing permissions and limitations
  17. * under the License.
  18. */
  19. package org.elasticsearch.cluster.metadata;
  20. import org.elasticsearch.ElasticSearchIllegalArgumentException;
  21. import org.elasticsearch.action.support.master.MasterNodeOperationRequest;
  22. import org.elasticsearch.cluster.ClusterService;
  23. import org.elasticsearch.cluster.ClusterState;
  24. import org.elasticsearch.cluster.TimeoutClusterStateUpdateTask;
  25. import org.elasticsearch.cluster.action.index.NodeIndicesStateUpdatedAction;
  26. import org.elasticsearch.cluster.block.ClusterBlock;
  27. import org.elasticsearch.cluster.block.ClusterBlockLevel;
  28. import org.elasticsearch.cluster.block.ClusterBlocks;
  29. import org.elasticsearch.cluster.routing.IndexRoutingTable;
  30. import org.elasticsearch.cluster.routing.IndexShardRoutingTable;
  31. import org.elasticsearch.cluster.routing.RoutingTable;
  32. import org.elasticsearch.cluster.routing.allocation.AllocationService;
  33. import org.elasticsearch.cluster.routing.allocation.RoutingAllocation;
  34. import org.elasticsearch.common.Priority;
  35. import org.elasticsearch.common.component.AbstractComponent;
  36. import org.elasticsearch.common.inject.Inject;
  37. import org.elasticsearch.common.settings.Settings;
  38. import org.elasticsearch.common.unit.TimeValue;
  39. import org.elasticsearch.index.Index;
  40. import org.elasticsearch.indices.IndexMissingException;
  41. import org.elasticsearch.indices.IndexPrimaryShardNotAllocatedException;
  42. import org.elasticsearch.rest.RestStatus;
  43. import java.util.ArrayList;
  44. import java.util.Arrays;
  45. import java.util.List;
  46. import java.util.concurrent.atomic.AtomicBoolean;
  47. import java.util.concurrent.atomic.AtomicInteger;
  48. /**
  49. *
  50. */
  51. public class MetaDataIndexStateService extends AbstractComponent {
  52. public static final ClusterBlock INDEX_CLOSED_BLOCK = new ClusterBlock(4, "index closed", false, false, RestStatus.FORBIDDEN, ClusterBlockLevel.READ_WRITE);
  53. private final ClusterService clusterService;
  54. private final AllocationService allocationService;
  55. private final NodeIndicesStateUpdatedAction indicesStateUpdatedAction;
  56. @Inject
  57. public MetaDataIndexStateService(Settings settings, ClusterService clusterService, AllocationService allocationService, NodeIndicesStateUpdatedAction indicesStateUpdatedAction) {
  58. super(settings);
  59. this.clusterService = clusterService;
  60. this.allocationService = allocationService;
  61. this.indicesStateUpdatedAction = indicesStateUpdatedAction;
  62. }
  63. public void closeIndex(final Request request, final Listener listener) {
  64. if (request.indices == null || request.indices.length == 0) {
  65. throw new ElasticSearchIllegalArgumentException("Index name is required");
  66. }
  67. final String indicesAsString = Arrays.toString(request.indices);
  68. clusterService.submitStateUpdateTask("close-indices " + indicesAsString, Priority.URGENT, new TimeoutClusterStateUpdateTask() {
  69. @Override
  70. public TimeValue timeout() {
  71. return request.masterTimeout;
  72. }
  73. @Override
  74. public void onFailure(String source, Throwable t) {
  75. listener.onFailure(t);
  76. }
  77. @Override
  78. public ClusterState execute(ClusterState currentState) {
  79. List<String> indicesToClose = new ArrayList<String>();
  80. for (String index : request.indices) {
  81. IndexMetaData indexMetaData = currentState.metaData().index(index);
  82. if (indexMetaData == null) {
  83. throw new IndexMissingException(new Index(index));
  84. }
  85. if (indexMetaData.state() != IndexMetaData.State.CLOSE) {
  86. IndexRoutingTable indexRoutingTable = currentState.routingTable().index(index);
  87. for (IndexShardRoutingTable shard : indexRoutingTable) {
  88. if (!shard.primaryAllocatedPostApi()) {
  89. throw new IndexPrimaryShardNotAllocatedException(new Index(index));
  90. }
  91. }
  92. indicesToClose.add(index);
  93. }
  94. }
  95. if (indicesToClose.isEmpty()) {
  96. return currentState;
  97. }
  98. logger.info("closing indices [{}]", indicesAsString);
  99. MetaData.Builder mdBuilder = MetaData.builder()
  100. .metaData(currentState.metaData());
  101. ClusterBlocks.Builder blocksBuilder = ClusterBlocks.builder()
  102. .blocks(currentState.blocks());
  103. for (String index : indicesToClose) {
  104. mdBuilder.put(IndexMetaData.newIndexMetaDataBuilder(currentState.metaData().index(index)).state(IndexMetaData.State.CLOSE));
  105. blocksBuilder.addIndexBlock(index, INDEX_CLOSED_BLOCK);
  106. }
  107. ClusterState updatedState = ClusterState.builder().state(currentState).metaData(mdBuilder).blocks(blocksBuilder).build();
  108. RoutingTable.Builder rtBuilder = RoutingTable.builder()
  109. .routingTable(currentState.routingTable());
  110. for (String index : indicesToClose) {
  111. rtBuilder.remove(index);
  112. }
  113. RoutingAllocation.Result routingResult = allocationService.reroute(ClusterState.builder().state(updatedState).routingTable(rtBuilder).build());
  114. ClusterState newClusterState = ClusterState.builder().state(updatedState).routingResult(routingResult).build();
  115. waitForOtherNodes(newClusterState, listener, request.timeout);
  116. return newClusterState;
  117. }
  118. @Override
  119. public void clusterStateProcessed(String source, ClusterState oldState, ClusterState newState) {
  120. if (oldState == newState) {
  121. // we didn't do anything, callback
  122. listener.onResponse(new Response(true));
  123. }
  124. }
  125. });
  126. }
  127. public void openIndex(final Request request, final Listener listener) {
  128. if (request.indices == null || request.indices.length == 0) {
  129. throw new ElasticSearchIllegalArgumentException("Index name is required");
  130. }
  131. final String indicesAsString = Arrays.toString(request.indices);
  132. clusterService.submitStateUpdateTask("open-indices " + indicesAsString, Priority.URGENT, new TimeoutClusterStateUpdateTask() {
  133. @Override
  134. public TimeValue timeout() {
  135. return request.masterTimeout;
  136. }
  137. @Override
  138. public void onFailure(String source, Throwable t) {
  139. listener.onFailure(t);
  140. }
  141. @Override
  142. public ClusterState execute(ClusterState currentState) {
  143. List<String> indicesToOpen = new ArrayList<String>();
  144. for (String index : request.indices) {
  145. IndexMetaData indexMetaData = currentState.metaData().index(index);
  146. if (indexMetaData == null) {
  147. throw new IndexMissingException(new Index(index));
  148. }
  149. if (indexMetaData.state() != IndexMetaData.State.OPEN) {
  150. indicesToOpen.add(index);
  151. }
  152. }
  153. if (indicesToOpen.isEmpty()) {
  154. return currentState;
  155. }
  156. logger.info("opening indices [{}]", indicesAsString);
  157. MetaData.Builder mdBuilder = MetaData.builder()
  158. .metaData(currentState.metaData());
  159. ClusterBlocks.Builder blocksBuilder = ClusterBlocks.builder()
  160. .blocks(currentState.blocks());
  161. for (String index : indicesToOpen) {
  162. mdBuilder.put(IndexMetaData.newIndexMetaDataBuilder(currentState.metaData().index(index)).state(IndexMetaData.State.OPEN));
  163. blocksBuilder.removeIndexBlock(index, INDEX_CLOSED_BLOCK);
  164. }
  165. ClusterState updatedState = ClusterState.builder().state(currentState).metaData(mdBuilder).blocks(blocksBuilder).build();
  166. RoutingTable.Builder rtBuilder = RoutingTable.builder()
  167. .routingTable(updatedState.routingTable());
  168. for (String index : indicesToOpen) {
  169. rtBuilder.addAsRecovery(updatedState.metaData().index(index));
  170. }
  171. RoutingAllocation.Result routingResult = allocationService.reroute(ClusterState.builder().state(updatedState).routingTable(rtBuilder).build());
  172. ClusterState newClusterState = ClusterState.builder().state(updatedState).routingResult(routingResult).build();
  173. waitForOtherNodes(newClusterState, listener, request.timeout);
  174. return newClusterState;
  175. }
  176. @Override
  177. public void clusterStateProcessed(String source, ClusterState oldState, ClusterState newState) {
  178. if (oldState == newState) {
  179. // we didn't do anything, callback
  180. listener.onResponse(new Response(true));
  181. }
  182. }
  183. });
  184. }
  185. private void waitForOtherNodes(ClusterState updatedState, Listener listener, TimeValue timeout) {
  186. // wait for responses from other nodes if needed
  187. int responseCount = updatedState.nodes().size();
  188. long version = updatedState.version() + 1;
  189. logger.trace("waiting for [{}] notifications with version [{}]", responseCount, version);
  190. indicesStateUpdatedAction.add(new CountDownListener(responseCount, listener, version), timeout);
  191. }
  192. public static interface Listener {
  193. void onResponse(Response response);
  194. void onFailure(Throwable t);
  195. }
  196. public static class Request {
  197. final String[] indices;
  198. TimeValue timeout = TimeValue.timeValueSeconds(10);
  199. TimeValue masterTimeout = MasterNodeOperationRequest.DEFAULT_MASTER_NODE_TIMEOUT;
  200. public Request(String[] indices) {
  201. this.indices = indices;
  202. }
  203. public Request timeout(TimeValue timeout) {
  204. this.timeout = timeout;
  205. return this;
  206. }
  207. public Request masterTimeout(TimeValue masterTimeout) {
  208. this.masterTimeout = masterTimeout;
  209. return this;
  210. }
  211. }
  212. public static class Response {
  213. private final boolean acknowledged;
  214. public Response(boolean acknowledged) {
  215. this.acknowledged = acknowledged;
  216. }
  217. public boolean acknowledged() {
  218. return acknowledged;
  219. }
  220. }
  221. private class CountDownListener implements NodeIndicesStateUpdatedAction.Listener {
  222. private final AtomicBoolean notified = new AtomicBoolean();
  223. private final AtomicInteger countDown;
  224. private final Listener listener;
  225. private final long version;
  226. public CountDownListener(int countDown, Listener listener, long version) {
  227. this.countDown = new AtomicInteger(countDown);
  228. this.listener = listener;
  229. this.version = version;
  230. }
  231. @Override
  232. public void onIndexStateUpdated(NodeIndicesStateUpdatedAction.NodeIndexStateUpdatedResponse response) {
  233. if (version <= response.version()) {
  234. logger.debug("Received NodeIndexStateUpdatedResponse with version [{}] from [{}]", response.version(), response.nodeId());
  235. if (countDown.decrementAndGet() == 0) {
  236. indicesStateUpdatedAction.remove(this);
  237. if (notified.compareAndSet(false, true)) {
  238. logger.debug("NodeIndexStateUpdated was acknowledged by all expected nodes, returning");
  239. listener.onResponse(new Response(true));
  240. }
  241. }
  242. }
  243. }
  244. @Override
  245. public void onTimeout() {
  246. indicesStateUpdatedAction.remove(this);
  247. if (notified.compareAndSet(false, true)) {
  248. listener.onResponse(new Response(false));
  249. }
  250. }
  251. }
  252. }