PageRenderTime 44ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/modules/elasticsearch/src/main/java/org/elasticsearch/indices/memory/IndexingMemoryBufferController.java

https://github.com/avar/elasticsearch
Java | 257 lines | 192 code | 33 blank | 32 comment | 41 complexity | 11657e97030b7b8539f8554e681561ff MD5 | raw file
  1. /*
  2. * Licensed to Elastic Search 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. Elastic Search 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.indices.memory;
  20. import org.elasticsearch.ElasticSearchException;
  21. import org.elasticsearch.common.collect.Maps;
  22. import org.elasticsearch.common.component.AbstractLifecycleComponent;
  23. import org.elasticsearch.common.inject.Inject;
  24. import org.elasticsearch.common.settings.Settings;
  25. import org.elasticsearch.common.unit.ByteSizeUnit;
  26. import org.elasticsearch.common.unit.ByteSizeValue;
  27. import org.elasticsearch.common.unit.TimeValue;
  28. import org.elasticsearch.index.engine.Engine;
  29. import org.elasticsearch.index.engine.EngineClosedException;
  30. import org.elasticsearch.index.engine.FlushNotAllowedEngineException;
  31. import org.elasticsearch.index.service.IndexService;
  32. import org.elasticsearch.index.shard.ShardId;
  33. import org.elasticsearch.index.shard.service.IndexShard;
  34. import org.elasticsearch.index.shard.service.InternalIndexShard;
  35. import org.elasticsearch.index.translog.Translog;
  36. import org.elasticsearch.indices.IndicesLifecycle;
  37. import org.elasticsearch.indices.IndicesService;
  38. import org.elasticsearch.monitor.jvm.JvmInfo;
  39. import org.elasticsearch.threadpool.ThreadPool;
  40. import java.util.Map;
  41. import java.util.concurrent.ScheduledFuture;
  42. /**
  43. * @author kimchy (shay.banon)
  44. */
  45. public class IndexingMemoryBufferController extends AbstractLifecycleComponent<IndexingMemoryBufferController> {
  46. private final ThreadPool threadPool;
  47. private final IndicesService indicesService;
  48. private final ByteSizeValue indexingBuffer;
  49. private final ByteSizeValue minShardIndexBufferSize;
  50. private final ByteSizeValue maxShardIndexBufferSize;
  51. private final TimeValue inactiveTime;
  52. private final TimeValue interval;
  53. private final Listener listener = new Listener();
  54. private final Map<ShardId, ShardIndexingStatus> shardsIndicesStatus = Maps.newHashMap();
  55. private volatile ScheduledFuture scheduler;
  56. private final Object mutex = new Object();
  57. @Inject public IndexingMemoryBufferController(Settings settings, ThreadPool threadPool, IndicesService indicesService) {
  58. super(settings);
  59. this.threadPool = threadPool;
  60. this.indicesService = indicesService;
  61. ByteSizeValue indexingBuffer;
  62. String indexingBufferSetting = componentSettings.get("index_buffer_size", "10%");
  63. if (indexingBufferSetting.endsWith("%")) {
  64. double percent = Double.parseDouble(indexingBufferSetting.substring(0, indexingBufferSetting.length() - 1));
  65. indexingBuffer = new ByteSizeValue((long) (((double) JvmInfo.jvmInfo().mem().heapMax().bytes()) * (percent / 100)));
  66. ByteSizeValue minIndexingBuffer = componentSettings.getAsBytesSize("min_index_buffer_size", new ByteSizeValue(48, ByteSizeUnit.MB));
  67. ByteSizeValue maxIndexingBuffer = componentSettings.getAsBytesSize("max_index_buffer_size", null);
  68. if (indexingBuffer.bytes() < minIndexingBuffer.bytes()) {
  69. indexingBuffer = minIndexingBuffer;
  70. }
  71. if (maxIndexingBuffer != null && indexingBuffer.bytes() > maxIndexingBuffer.bytes()) {
  72. indexingBuffer = maxIndexingBuffer;
  73. }
  74. } else {
  75. indexingBuffer = ByteSizeValue.parseBytesSizeValue(indexingBufferSetting, null);
  76. }
  77. this.indexingBuffer = indexingBuffer;
  78. this.minShardIndexBufferSize = componentSettings.getAsBytesSize("min_shard_index_buffer_size", new ByteSizeValue(4, ByteSizeUnit.MB));
  79. // LUCENE MONITOR: Based on this thread, currently (based on Mike), having a large buffer does not make a lot of sense: https://issues.apache.org/jira/browse/LUCENE-2324?focusedCommentId=13005155&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-13005155
  80. this.maxShardIndexBufferSize = componentSettings.getAsBytesSize("max_shard_index_buffer_size", new ByteSizeValue(512, ByteSizeUnit.MB));
  81. this.inactiveTime = componentSettings.getAsTime("shard_inactive_time", TimeValue.timeValueMinutes(30));
  82. // we need to have this relatively small to move a shard from inactive to active fast (enough)
  83. this.interval = componentSettings.getAsTime("interval", TimeValue.timeValueSeconds(30));
  84. logger.debug("using index_buffer_size [{}], with min_shard_index_buffer_size [{}], max_shard_index_buffer_size [{}], shard_inactive_time [{}]", this.indexingBuffer, this.minShardIndexBufferSize, this.maxShardIndexBufferSize, this.inactiveTime);
  85. }
  86. @Override protected void doStart() throws ElasticSearchException {
  87. indicesService.indicesLifecycle().addListener(listener);
  88. // its fine to run it on the scheduler thread, no busy work
  89. this.scheduler = threadPool.scheduleWithFixedDelay(new ShardsIndicesStatusChecker(), interval);
  90. }
  91. @Override protected void doStop() throws ElasticSearchException {
  92. indicesService.indicesLifecycle().removeListener(listener);
  93. if (scheduler != null) {
  94. scheduler.cancel(false);
  95. scheduler = null;
  96. }
  97. }
  98. @Override protected void doClose() throws ElasticSearchException {
  99. }
  100. class ShardsIndicesStatusChecker implements Runnable {
  101. @Override public void run() {
  102. synchronized (mutex) {
  103. boolean activeInactiveStatusChanges = false;
  104. for (IndexService indexService : indicesService) {
  105. for (IndexShard indexShard : indexService) {
  106. long time = threadPool.estimatedTimeInMillis();
  107. Translog translog = ((InternalIndexShard) indexShard).translog();
  108. ShardIndexingStatus status = shardsIndicesStatus.get(indexShard.shardId());
  109. if (status == null) { // not added yet
  110. continue;
  111. }
  112. // check if it is deemed to be inactive (sam translogId and numberOfOperations over a long period of time)
  113. if (status.translogId == translog.currentId() && translog.estimatedNumberOfOperations() == 0) {
  114. if (status.time == -1) { // first time
  115. status.time = time;
  116. }
  117. // inactive?
  118. if (!status.inactive) {
  119. // mark it as inactive only if enough time has passed and there are no ongoing merges going on...
  120. if ((time - status.time) > inactiveTime.millis() && indexShard.mergeStats().current() == 0) {
  121. try {
  122. ((InternalIndexShard) indexShard).engine().updateIndexingBufferSize(Engine.INACTIVE_SHARD_INDEXING_BUFFER);
  123. } catch (EngineClosedException e) {
  124. // ignore
  125. continue;
  126. } catch (FlushNotAllowedEngineException e) {
  127. // ignore
  128. continue;
  129. }
  130. // inactive for this amount of time, mark it
  131. status.inactive = true;
  132. activeInactiveStatusChanges = true;
  133. logger.debug("marking shard [{}][{}] as inactive (inactive_time[{}]) indexing wise, setting size to [{}]", indexShard.shardId().index().name(), indexShard.shardId().id(), inactiveTime, Engine.INACTIVE_SHARD_INDEXING_BUFFER);
  134. }
  135. }
  136. } else {
  137. if (status.inactive) {
  138. status.inactive = false;
  139. activeInactiveStatusChanges = true;
  140. logger.debug("marking shard [{}][{}] as active indexing wise", indexShard.shardId().index().name(), indexShard.shardId().id());
  141. }
  142. status.time = -1;
  143. }
  144. status.translogId = translog.currentId();
  145. status.translogNumberOfOperations = translog.estimatedNumberOfOperations();
  146. }
  147. }
  148. if (activeInactiveStatusChanges) {
  149. calcAndSetShardIndexingBuffer("shards became active/inactive (indexing wise)");
  150. }
  151. }
  152. }
  153. }
  154. class Listener extends IndicesLifecycle.Listener {
  155. @Override public void afterIndexShardCreated(IndexShard indexShard) {
  156. synchronized (mutex) {
  157. calcAndSetShardIndexingBuffer("created_shard[" + indexShard.shardId().index().name() + "][" + indexShard.shardId().id() + "]");
  158. shardsIndicesStatus.put(indexShard.shardId(), new ShardIndexingStatus());
  159. }
  160. }
  161. @Override public void afterIndexShardClosed(ShardId shardId, boolean delete) {
  162. synchronized (mutex) {
  163. calcAndSetShardIndexingBuffer("removed_shard[" + shardId.index().name() + "][" + shardId.id() + "]");
  164. shardsIndicesStatus.remove(shardId);
  165. }
  166. }
  167. }
  168. private void calcAndSetShardIndexingBuffer(String reason) {
  169. int shardsCount = countShards();
  170. if (shardsCount == 0) {
  171. return;
  172. }
  173. ByteSizeValue shardIndexingBufferSize = calcShardIndexingBuffer(shardsCount);
  174. if (shardIndexingBufferSize == null) {
  175. return;
  176. }
  177. if (shardIndexingBufferSize.bytes() < minShardIndexBufferSize.bytes()) {
  178. shardIndexingBufferSize = minShardIndexBufferSize;
  179. }
  180. if (shardIndexingBufferSize.bytes() > maxShardIndexBufferSize.bytes()) {
  181. shardIndexingBufferSize = maxShardIndexBufferSize;
  182. }
  183. logger.debug("recalculating shard indexing buffer (reason={}), total is [{}] with [{}] active shards, each shard set to [{}]", reason, indexingBuffer, shardsCount, shardIndexingBufferSize);
  184. for (IndexService indexService : indicesService) {
  185. for (IndexShard indexShard : indexService) {
  186. ShardIndexingStatus status = shardsIndicesStatus.get(indexShard.shardId());
  187. if (status == null || !status.inactive) {
  188. try {
  189. ((InternalIndexShard) indexShard).engine().updateIndexingBufferSize(shardIndexingBufferSize);
  190. } catch (EngineClosedException e) {
  191. // ignore
  192. continue;
  193. } catch (FlushNotAllowedEngineException e) {
  194. // ignore
  195. continue;
  196. } catch (Exception e) {
  197. logger.warn("failed to set shard [{}][{}] index buffer to [{}]", indexShard.shardId().index().name(), indexShard.shardId().id(), shardIndexingBufferSize);
  198. }
  199. }
  200. }
  201. }
  202. }
  203. private ByteSizeValue calcShardIndexingBuffer(int shardsCount) {
  204. return new ByteSizeValue(indexingBuffer.bytes() / shardsCount);
  205. }
  206. private int countShards() {
  207. int shardsCount = 0;
  208. for (IndexService indexService : indicesService) {
  209. for (IndexShard indexShard : indexService) {
  210. ShardIndexingStatus status = shardsIndicesStatus.get(indexShard.shardId());
  211. if (status == null || !status.inactive) {
  212. shardsCount++;
  213. }
  214. }
  215. }
  216. return shardsCount;
  217. }
  218. static class ShardIndexingStatus {
  219. long translogId = -1;
  220. int translogNumberOfOperations = -1;
  221. boolean inactive = false;
  222. long time = -1; // contains the first time we saw this shard with no operations done on it
  223. }
  224. }