ClusterState.java 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195
  1. /*
  2. * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
  3. * or more contributor license agreements. Licensed under the Elastic License
  4. * 2.0 and the Server Side Public License, v 1; you may not use this file except
  5. * in compliance with, at your election, the Elastic License 2.0 or the Server
  6. * Side Public License, v 1.
  7. */
  8. package org.elasticsearch.cluster;
  9. import org.elasticsearch.TransportVersion;
  10. import org.elasticsearch.TransportVersions;
  11. import org.elasticsearch.Version;
  12. import org.elasticsearch.action.support.master.TransportMasterNodeAction;
  13. import org.elasticsearch.cluster.block.ClusterBlock;
  14. import org.elasticsearch.cluster.block.ClusterBlocks;
  15. import org.elasticsearch.cluster.coordination.ClusterStatePublisher;
  16. import org.elasticsearch.cluster.coordination.CoordinationMetadata;
  17. import org.elasticsearch.cluster.coordination.CoordinationMetadata.VotingConfigExclusion;
  18. import org.elasticsearch.cluster.coordination.CoordinationMetadata.VotingConfiguration;
  19. import org.elasticsearch.cluster.coordination.NoMasterBlockService;
  20. import org.elasticsearch.cluster.metadata.IndexMetadata;
  21. import org.elasticsearch.cluster.metadata.Metadata;
  22. import org.elasticsearch.cluster.node.DiscoveryNode;
  23. import org.elasticsearch.cluster.node.DiscoveryNodes;
  24. import org.elasticsearch.cluster.routing.RoutingNodes;
  25. import org.elasticsearch.cluster.routing.RoutingTable;
  26. import org.elasticsearch.cluster.service.ClusterApplierService;
  27. import org.elasticsearch.cluster.service.ClusterService;
  28. import org.elasticsearch.cluster.service.MasterService;
  29. import org.elasticsearch.cluster.version.CompatibilityVersions;
  30. import org.elasticsearch.common.Priority;
  31. import org.elasticsearch.common.Strings;
  32. import org.elasticsearch.common.UUIDs;
  33. import org.elasticsearch.common.bytes.BytesReference;
  34. import org.elasticsearch.common.collect.ImmutableOpenMap;
  35. import org.elasticsearch.common.collect.Iterators;
  36. import org.elasticsearch.common.io.stream.BytesStreamOutput;
  37. import org.elasticsearch.common.io.stream.NamedWriteableAwareStreamInput;
  38. import org.elasticsearch.common.io.stream.NamedWriteableRegistry;
  39. import org.elasticsearch.common.io.stream.StreamInput;
  40. import org.elasticsearch.common.io.stream.StreamOutput;
  41. import org.elasticsearch.common.io.stream.VersionedNamedWriteable;
  42. import org.elasticsearch.common.io.stream.Writeable;
  43. import org.elasticsearch.common.xcontent.ChunkedToXContent;
  44. import org.elasticsearch.common.xcontent.ChunkedToXContentHelper;
  45. import org.elasticsearch.core.Nullable;
  46. import org.elasticsearch.core.SuppressForbidden;
  47. import org.elasticsearch.indices.SystemIndexDescriptor;
  48. import org.elasticsearch.xcontent.ToXContent;
  49. import org.elasticsearch.xcontent.XContent;
  50. import java.io.IOException;
  51. import java.util.Collections;
  52. import java.util.EnumSet;
  53. import java.util.HashMap;
  54. import java.util.Iterator;
  55. import java.util.Map;
  56. import java.util.Objects;
  57. import java.util.Set;
  58. import java.util.TreeSet;
  59. import java.util.concurrent.Executor;
  60. import java.util.function.Consumer;
  61. import java.util.function.Function;
  62. import static org.elasticsearch.gateway.GatewayService.STATE_NOT_RECOVERED_BLOCK;
  63. /**
  64. * Represents the state of the cluster, held in memory on all nodes in the cluster with updates coordinated by the elected master.
  65. * <p>
  66. * Conceptually immutable, but in practice it has a few components like {@link RoutingNodes} which are pure functions of the immutable state
  67. * but are expensive to compute so they are built on-demand if needed.
  68. * <p>
  69. * The {@link Metadata} portion is written to disk on each update so it persists across full-cluster restarts. The rest of this data is
  70. * maintained only in-memory and resets back to its initial state on a full-cluster restart, but it is held on all nodes so it persists
  71. * across master elections (and therefore is preserved in a rolling restart).
  72. * <p>
  73. * Updates are triggered by submitting tasks to the {@link MasterService} on the elected master, typically using a {@link
  74. * TransportMasterNodeAction} to route a request to the master on which the task is submitted via a queue obtained with {@link
  75. * ClusterService#createTaskQueue}, which has an associated priority. Submitted tasks have an associated
  76. * timeout. Tasks are processed in priority order, so a flood of higher-priority tasks can starve lower-priority ones from running.
  77. * Therefore, avoid priorities other than {@link Priority#NORMAL} where possible. Tasks associated with client actions should typically have
  78. * a timeout, or otherwise be sensitive to client cancellations, to avoid surprises caused by the execution of stale tasks long after they
  79. * are submitted (since clients themselves tend to time out). In contrast, internal tasks can reasonably have an infinite timeout,
  80. * especially if a timeout would simply trigger a retry.
  81. * <p>
  82. * Tasks that share the same {@link ClusterStateTaskExecutor} instance are processed as a batch. Each batch of tasks yields a new {@link
  83. * ClusterState} which is published to the cluster by {@link ClusterStatePublisher#publish}. Publication usually works by sending a diff,
  84. * computed via the {@link Diffable} interface, rather than the full state, although it will fall back to sending the full state if the
  85. * receiving node is new or it has missed out on an intermediate state for some reason. States and diffs are published using the transport
  86. * protocol, i.e. the {@link Writeable} interface and friends.
  87. * <p>
  88. * When committed, the new state is <i>applied</i> which exposes it to the node via {@link ClusterStateApplier} and {@link
  89. * ClusterStateListener} callbacks registered with the {@link ClusterApplierService}. The new state is also made available via {@link
  90. * ClusterService#state()}. The appliers are notified (in no particular order) before {@link ClusterService#state()} is updated, and the
  91. * listeners are notified (in no particular order) afterwards. Cluster state updates run in sequence, one-by-one, so they can be a
  92. * performance bottleneck. See the JavaDocs on the linked classes and methods for more details.
  93. * <p>
  94. * Cluster state updates can be used to trigger various actions via a {@link ClusterStateListener} rather than using a timer.
  95. * <p>
  96. * Implements {@link ChunkedToXContent} to be exposed in REST APIs (e.g. {@code GET _cluster/state} and {@code POST _cluster/reroute}) and
  97. * to be indexed by monitoring, mostly just for diagnostics purposes. The {@link XContent} representation does not need to be 100% faithful
  98. * since we never reconstruct a cluster state from its XContent representation, but the more faithful it is the more useful it is for
  99. * diagnostics. Note that the {@link XContent} representation of the {@link Metadata} portion does have to be faithful (in {@link
  100. * Metadata.XContentContext#GATEWAY} context) since this is how it persists across full cluster restarts.
  101. * <p>
  102. * Security-sensitive data such as passwords or private keys should not be stored in the cluster state, since the contents of the cluster
  103. * state are exposed in various APIs.
  104. */
  105. public class ClusterState implements ChunkedToXContent, Diffable<ClusterState> {
  106. public static final ClusterState EMPTY_STATE = builder(ClusterName.DEFAULT).build();
  107. public interface Custom extends NamedDiffable<Custom>, ChunkedToXContent {
  108. /**
  109. * Returns <code>true</code> iff this {@link Custom} is private to the cluster and should never be sent to a client.
  110. * The default is <code>false</code>;
  111. */
  112. default boolean isPrivate() {
  113. return false;
  114. }
  115. /**
  116. * Serialize this {@link Custom} for diagnostic purposes, exposed by the <pre>GET _cluster/state</pre> API etc. The XContent
  117. * representation does not need to be 100% faithful since we never reconstruct a cluster state from its XContent representation, but
  118. * the more faithful it is the more useful it is for diagnostics.
  119. */
  120. @Override
  121. Iterator<? extends ToXContent> toXContentChunked(ToXContent.Params params);
  122. }
  123. private static final NamedDiffableValueSerializer<Custom> CUSTOM_VALUE_SERIALIZER = new NamedDiffableValueSerializer<>(Custom.class);
  124. private static final DiffableUtils.ValueSerializer<String, CompatibilityVersions> COMPATIBILITY_VERSIONS_VALUE_SERIALIZER =
  125. new DiffableUtils.NonDiffableValueSerializer<>() {
  126. @Override
  127. public void write(CompatibilityVersions value, StreamOutput out) throws IOException {
  128. value.writeTo(out);
  129. }
  130. @Override
  131. public CompatibilityVersions read(StreamInput in, String key) throws IOException {
  132. return CompatibilityVersions.readVersion(in);
  133. }
  134. };
  135. public static final String UNKNOWN_UUID = "_na_";
  136. public static final long UNKNOWN_VERSION = -1;
  137. /**
  138. * Monotonically increasing on (and therefore uniquely identifies) <i>committed</i> states. However sometimes a state is created/applied
  139. * without committing it, for instance to add a {@link NoMasterBlockService#getNoMasterBlock}.
  140. */
  141. private final long version;
  142. /**
  143. * Uniquely identifies this state, even if the state is not committed.
  144. */
  145. private final String stateUUID;
  146. /**
  147. * Describes the location (and state) of all shards, used for routing actions such as searches to the relevant shards.
  148. */
  149. private final RoutingTable routingTable;
  150. private final DiscoveryNodes nodes;
  151. private final Map<String, CompatibilityVersions> compatibilityVersions;
  152. private final CompatibilityVersions minVersions;
  153. private final ClusterFeatures clusterFeatures;
  154. private final Metadata metadata;
  155. private final ClusterBlocks blocks;
  156. private final Map<String, Custom> customs;
  157. private final ClusterName clusterName;
  158. private final boolean wasReadFromDiff;
  159. // built on demand
  160. private volatile RoutingNodes routingNodes;
  161. public ClusterState(long version, String stateUUID, ClusterState state) {
  162. this(
  163. state.clusterName,
  164. version,
  165. stateUUID,
  166. state.metadata(),
  167. state.routingTable(),
  168. state.nodes(),
  169. state.compatibilityVersions,
  170. state.clusterFeatures(),
  171. state.blocks(),
  172. state.customs(),
  173. false,
  174. state.routingNodes
  175. );
  176. }
  177. public ClusterState(
  178. ClusterName clusterName,
  179. long version,
  180. String stateUUID,
  181. Metadata metadata,
  182. RoutingTable routingTable,
  183. DiscoveryNodes nodes,
  184. Map<String, CompatibilityVersions> compatibilityVersions,
  185. ClusterFeatures clusterFeatures,
  186. ClusterBlocks blocks,
  187. Map<String, Custom> customs,
  188. boolean wasReadFromDiff,
  189. @Nullable RoutingNodes routingNodes
  190. ) {
  191. this.version = version;
  192. this.stateUUID = stateUUID;
  193. this.clusterName = clusterName;
  194. this.metadata = metadata;
  195. this.routingTable = routingTable;
  196. this.nodes = nodes;
  197. this.compatibilityVersions = Map.copyOf(compatibilityVersions);
  198. this.clusterFeatures = clusterFeatures;
  199. this.blocks = blocks;
  200. this.customs = customs;
  201. this.wasReadFromDiff = wasReadFromDiff;
  202. this.routingNodes = routingNodes;
  203. assert assertConsistentRoutingNodes(routingTable, nodes, routingNodes);
  204. this.minVersions = blocks.hasGlobalBlock(STATE_NOT_RECOVERED_BLOCK)
  205. ? new CompatibilityVersions(TransportVersions.MINIMUM_COMPATIBLE, Map.of()) // empty map because cluster state is unknown
  206. : CompatibilityVersions.minimumVersions(compatibilityVersions.values());
  207. }
  208. private static boolean assertConsistentRoutingNodes(
  209. RoutingTable routingTable,
  210. DiscoveryNodes nodes,
  211. @Nullable RoutingNodes routingNodes
  212. ) {
  213. if (routingNodes == null) {
  214. return true;
  215. }
  216. final RoutingNodes expected = RoutingNodes.immutable(routingTable, nodes);
  217. assert routingNodes.equals(expected)
  218. : "RoutingNodes [" + routingNodes + "] are not consistent with this cluster state [" + expected + "]";
  219. return true;
  220. }
  221. public long term() {
  222. return coordinationMetadata().term();
  223. }
  224. public long version() {
  225. return this.version;
  226. }
  227. public long getVersion() {
  228. return version();
  229. }
  230. /**
  231. * This stateUUID is automatically generated for for each version of cluster state. It is used to make sure that
  232. * we are applying diffs to the right previous state.
  233. */
  234. public String stateUUID() {
  235. return this.stateUUID;
  236. }
  237. public DiscoveryNodes nodes() {
  238. return this.nodes;
  239. }
  240. public DiscoveryNodes getNodes() {
  241. return nodes();
  242. }
  243. /**
  244. * Returns the set of nodes that should be exposed to things like REST handlers that behave differently depending on the nodes in the
  245. * cluster and their versions. Specifically, if the cluster has properly formed then this is the nodes in the last-applied cluster
  246. * state, but if the cluster has not properly formed then no nodes are returned.
  247. *
  248. * @return the nodes in the cluster if the cluster has properly formed, otherwise an empty set of nodes.
  249. */
  250. public DiscoveryNodes nodesIfRecovered() {
  251. return blocks.hasGlobalBlock(STATE_NOT_RECOVERED_BLOCK) ? DiscoveryNodes.EMPTY_NODES : nodes;
  252. }
  253. public boolean clusterRecovered() {
  254. return blocks.hasGlobalBlock(STATE_NOT_RECOVERED_BLOCK) == false;
  255. }
  256. public Map<String, CompatibilityVersions> compatibilityVersions() {
  257. return this.compatibilityVersions;
  258. }
  259. public boolean hasMixedSystemIndexVersions() {
  260. return compatibilityVersions.values()
  261. .stream()
  262. .anyMatch(e -> e.systemIndexMappingsVersion().equals(minVersions.systemIndexMappingsVersion()) == false);
  263. }
  264. public TransportVersion getMinTransportVersion() {
  265. return this.minVersions.transportVersion();
  266. }
  267. public Map<String, SystemIndexDescriptor.MappingsVersion> getMinSystemIndexMappingVersions() {
  268. return this.minVersions.systemIndexMappingsVersion();
  269. }
  270. public ClusterFeatures clusterFeatures() {
  271. return clusterFeatures;
  272. }
  273. public Metadata metadata() {
  274. return this.metadata;
  275. }
  276. public Metadata getMetadata() {
  277. return metadata();
  278. }
  279. public CoordinationMetadata coordinationMetadata() {
  280. return metadata.coordinationMetadata();
  281. }
  282. public RoutingTable routingTable() {
  283. return routingTable;
  284. }
  285. public RoutingTable getRoutingTable() {
  286. return routingTable();
  287. }
  288. public ClusterBlocks blocks() {
  289. return this.blocks;
  290. }
  291. public ClusterBlocks getBlocks() {
  292. return blocks;
  293. }
  294. public Map<String, Custom> customs() {
  295. return this.customs;
  296. }
  297. public Map<String, Custom> getCustoms() {
  298. return this.customs;
  299. }
  300. @SuppressWarnings("unchecked")
  301. public <T extends Custom> T custom(String type) {
  302. return (T) customs.get(type);
  303. }
  304. @SuppressWarnings("unchecked")
  305. public <T extends Custom> T custom(String type, T defaultValue) {
  306. return (T) customs.getOrDefault(type, defaultValue);
  307. }
  308. public ClusterName getClusterName() {
  309. return this.clusterName;
  310. }
  311. public VotingConfiguration getLastAcceptedConfiguration() {
  312. return coordinationMetadata().getLastAcceptedConfiguration();
  313. }
  314. public VotingConfiguration getLastCommittedConfiguration() {
  315. return coordinationMetadata().getLastCommittedConfiguration();
  316. }
  317. public Set<VotingConfigExclusion> getVotingConfigExclusions() {
  318. return coordinationMetadata().getVotingConfigExclusions();
  319. }
  320. /**
  321. * Returns a built (on demand) routing nodes view of the routing table.
  322. */
  323. public RoutingNodes getRoutingNodes() {
  324. RoutingNodes r = routingNodes;
  325. if (r != null) {
  326. return r;
  327. }
  328. r = buildRoutingNodes();
  329. return r;
  330. }
  331. private synchronized RoutingNodes buildRoutingNodes() {
  332. RoutingNodes r = routingNodes;
  333. if (r != null) {
  334. return r;
  335. }
  336. r = RoutingNodes.immutable(routingTable, nodes);
  337. routingNodes = r;
  338. return r;
  339. }
  340. /**
  341. * Returns a fresh mutable copy of the routing nodes view.
  342. */
  343. public RoutingNodes mutableRoutingNodes() {
  344. final RoutingNodes nodes = this.routingNodes;
  345. // use the cheaper copy constructor if we already computed the routing nodes for this state.
  346. if (nodes != null) {
  347. return nodes.mutableCopy();
  348. }
  349. // we don't have any routing nodes for this state, likely because it's a temporary state in the reroute logic, don't compute an
  350. // immutable copy that will never be used and instead directly build a mutable copy
  351. return RoutingNodes.mutable(routingTable, this.nodes);
  352. }
  353. /**
  354. * Initialize data structures that lazy computed for this instance in the background by using the giving executor.
  355. * @param executor executor to run initialization tasks on
  356. */
  357. public void initializeAsync(Executor executor) {
  358. if (routingNodes == null) {
  359. executor.execute(new Runnable() {
  360. @Override
  361. public void run() {
  362. getRoutingNodes();
  363. }
  364. @Override
  365. public String toString() {
  366. return "async initialization of routing nodes for cluster state " + version();
  367. }
  368. });
  369. }
  370. if (metadata.indicesLookupInitialized() == false) {
  371. executor.execute(new Runnable() {
  372. @Override
  373. public void run() {
  374. metadata.getIndicesLookup();
  375. }
  376. @Override
  377. public String toString() {
  378. return "async initialization of indices lookup for cluster state " + version();
  379. }
  380. });
  381. }
  382. }
  383. @Override
  384. public String toString() {
  385. StringBuilder sb = new StringBuilder();
  386. final String TAB = " ";
  387. sb.append("cluster uuid: ")
  388. .append(metadata.clusterUUID())
  389. .append(" [committed: ")
  390. .append(metadata.clusterUUIDCommitted())
  391. .append("]")
  392. .append("\n");
  393. sb.append("version: ").append(version).append("\n");
  394. sb.append("state uuid: ").append(stateUUID).append("\n");
  395. sb.append("from_diff: ").append(wasReadFromDiff).append("\n");
  396. sb.append("meta data version: ").append(metadata.version()).append("\n");
  397. sb.append(TAB).append("coordination_metadata:\n");
  398. sb.append(TAB).append(TAB).append("term: ").append(coordinationMetadata().term()).append("\n");
  399. sb.append(TAB)
  400. .append(TAB)
  401. .append("last_committed_config: ")
  402. .append(coordinationMetadata().getLastCommittedConfiguration())
  403. .append("\n");
  404. sb.append(TAB)
  405. .append(TAB)
  406. .append("last_accepted_config: ")
  407. .append(coordinationMetadata().getLastAcceptedConfiguration())
  408. .append("\n");
  409. sb.append(TAB).append(TAB).append("voting tombstones: ").append(coordinationMetadata().getVotingConfigExclusions()).append("\n");
  410. for (IndexMetadata indexMetadata : metadata) {
  411. sb.append(TAB).append(indexMetadata.getIndex());
  412. sb.append(": v[")
  413. .append(indexMetadata.getVersion())
  414. .append("], mv[")
  415. .append(indexMetadata.getMappingVersion())
  416. .append("], sv[")
  417. .append(indexMetadata.getSettingsVersion())
  418. .append("], av[")
  419. .append(indexMetadata.getAliasesVersion())
  420. .append("]\n");
  421. for (int shard = 0; shard < indexMetadata.getNumberOfShards(); shard++) {
  422. sb.append(TAB).append(TAB).append(shard).append(": ");
  423. sb.append("p_term [").append(indexMetadata.primaryTerm(shard)).append("], ");
  424. sb.append("isa_ids ").append(indexMetadata.inSyncAllocationIds(shard)).append("\n");
  425. }
  426. }
  427. if (metadata.customs().isEmpty() == false) {
  428. sb.append("metadata customs:\n");
  429. for (final Map.Entry<String, Metadata.Custom> cursor : metadata.customs().entrySet()) {
  430. final String type = cursor.getKey();
  431. final Metadata.Custom custom = cursor.getValue();
  432. sb.append(TAB).append(type).append(": ").append(custom);
  433. }
  434. sb.append("\n");
  435. }
  436. sb.append(blocks());
  437. sb.append(nodes());
  438. if (compatibilityVersions.isEmpty() == false) {
  439. sb.append("node versions:\n");
  440. for (var tv : compatibilityVersions.entrySet()) {
  441. sb.append(TAB).append(tv.getKey()).append(": ").append(tv.getValue()).append("\n");
  442. }
  443. }
  444. sb.append("cluster features:\n");
  445. for (var nf : getNodeFeatures(clusterFeatures).entrySet()) {
  446. sb.append(TAB).append(nf.getKey()).append(": ").append(new TreeSet<>(nf.getValue())).append("\n");
  447. }
  448. sb.append(routingTable());
  449. sb.append(getRoutingNodes());
  450. if (customs.isEmpty() == false) {
  451. sb.append("customs:\n");
  452. for (Map.Entry<String, Custom> cursor : customs.entrySet()) {
  453. final String type = cursor.getKey();
  454. final Custom custom = cursor.getValue();
  455. sb.append(TAB).append(type).append(": ").append(custom);
  456. }
  457. }
  458. return sb.toString();
  459. }
  460. /**
  461. * a cluster state supersedes another state if they are from the same master and the version of this state is higher than that of the
  462. * other state.
  463. * <p>
  464. * In essence that means that all the changes from the other cluster state are also reflected by the current one
  465. */
  466. public boolean supersedes(ClusterState other) {
  467. return this.nodes().getMasterNodeId() != null
  468. && this.nodes().getMasterNodeId().equals(other.nodes().getMasterNodeId())
  469. && this.version() > other.version();
  470. }
  471. public enum Metric {
  472. VERSION("version"),
  473. MASTER_NODE("master_node"),
  474. BLOCKS("blocks"),
  475. NODES("nodes"),
  476. METADATA("metadata"),
  477. ROUTING_TABLE("routing_table"),
  478. ROUTING_NODES("routing_nodes"),
  479. CUSTOMS("customs");
  480. private static final Map<String, Metric> valueToEnum;
  481. static {
  482. valueToEnum = new HashMap<>();
  483. for (Metric metric : Metric.values()) {
  484. valueToEnum.put(metric.value, metric);
  485. }
  486. }
  487. private final String value;
  488. Metric(String value) {
  489. this.value = value;
  490. }
  491. public static EnumSet<Metric> parseString(String param, boolean ignoreUnknown) {
  492. String[] metrics = Strings.splitStringByCommaToArray(param);
  493. EnumSet<Metric> result = EnumSet.noneOf(Metric.class);
  494. for (String metric : metrics) {
  495. if ("_all".equals(metric)) {
  496. result = EnumSet.allOf(Metric.class);
  497. break;
  498. }
  499. Metric m = valueToEnum.get(metric);
  500. if (m == null) {
  501. if (ignoreUnknown == false) {
  502. throw new IllegalArgumentException("Unknown metric [" + metric + "]");
  503. }
  504. } else {
  505. result.add(m);
  506. }
  507. }
  508. return result;
  509. }
  510. @Override
  511. public String toString() {
  512. return value;
  513. }
  514. }
  515. private static <T> Iterator<ToXContent> chunkedSection(
  516. boolean condition,
  517. ToXContent before,
  518. Iterator<T> items,
  519. Function<T, Iterator<ToXContent>> fn,
  520. ToXContent after
  521. ) {
  522. return condition
  523. ? Iterators.concat(Iterators.single(before), Iterators.flatMap(items, fn::apply), Iterators.single(after))
  524. : Collections.emptyIterator();
  525. }
  526. @Override
  527. public Iterator<? extends ToXContent> toXContentChunked(ToXContent.Params outerParams) {
  528. final var metrics = Metric.parseString(outerParams.param("metric", "_all"), true);
  529. return Iterators.concat(
  530. // header chunk
  531. Iterators.single(((builder, params) -> {
  532. // always provide the cluster_uuid as part of the top-level response (also part of the metadata response)
  533. builder.field("cluster_uuid", metadata().clusterUUID());
  534. // state version info
  535. if (metrics.contains(Metric.VERSION)) {
  536. builder.field("version", version);
  537. builder.field("state_uuid", stateUUID);
  538. }
  539. // master node
  540. if (metrics.contains(Metric.MASTER_NODE)) {
  541. builder.field("master_node", nodes().getMasterNodeId());
  542. }
  543. return builder;
  544. })),
  545. // blocks
  546. chunkedSection(metrics.contains(Metric.BLOCKS), (builder, params) -> {
  547. builder.startObject("blocks");
  548. if (blocks().global().isEmpty() == false) {
  549. builder.startObject("global");
  550. for (ClusterBlock block : blocks().global()) {
  551. block.toXContent(builder, params);
  552. }
  553. builder.endObject();
  554. }
  555. if (blocks().indices().isEmpty() == false) {
  556. builder.startObject("indices");
  557. }
  558. return builder;
  559. }, blocks.indices().entrySet().iterator(), entry -> Iterators.single((builder, params) -> {
  560. builder.startObject(entry.getKey());
  561. for (ClusterBlock block : entry.getValue()) {
  562. block.toXContent(builder, params);
  563. }
  564. return builder.endObject();
  565. }), (builder, params) -> {
  566. if (blocks().indices().isEmpty() == false) {
  567. builder.endObject();
  568. }
  569. return builder.endObject();
  570. }),
  571. // nodes
  572. chunkedSection(
  573. metrics.contains(Metric.NODES),
  574. (builder, params) -> builder.startObject("nodes"),
  575. nodes.iterator(),
  576. Iterators::single,
  577. (builder, params) -> builder.endObject()
  578. ),
  579. // per-node version information
  580. chunkedSection(
  581. metrics.contains(Metric.NODES),
  582. (builder, params) -> builder.startArray("nodes_versions"),
  583. compatibilityVersions.entrySet().iterator(),
  584. e -> Iterators.single((builder, params) -> {
  585. builder.startObject().field("node_id", e.getKey());
  586. e.getValue().toXContent(builder, params);
  587. return builder.endObject();
  588. }),
  589. (builder, params) -> builder.endArray()
  590. ),
  591. // per-node feature information
  592. metrics.contains(Metric.NODES)
  593. ? Iterators.concat(
  594. Iterators.<ToXContent>single((b, p) -> b.field("nodes_features")),
  595. clusterFeatures.toXContentChunked(outerParams)
  596. )
  597. : Collections.emptyIterator(),
  598. // metadata
  599. metrics.contains(Metric.METADATA) ? metadata.toXContentChunked(outerParams) : Collections.emptyIterator(),
  600. // routing table
  601. chunkedSection(
  602. metrics.contains(Metric.ROUTING_TABLE),
  603. (builder, params) -> builder.startObject("routing_table").startObject("indices"),
  604. routingTable().iterator(),
  605. indexRoutingTable -> {
  606. Iterator<Iterator<ToXContent>> input = Iterators.forRange(0, indexRoutingTable.size(), shardId -> {
  607. final var indexShardRoutingTable = indexRoutingTable.shard(shardId);
  608. return Iterators.concat(
  609. Iterators.single(
  610. (builder, params) -> builder.startArray(Integer.toString(indexShardRoutingTable.shardId().id()))
  611. ),
  612. Iterators.forRange(
  613. 0,
  614. indexShardRoutingTable.size(),
  615. copy -> (builder, params) -> indexShardRoutingTable.shard(copy).toXContent(builder, params)
  616. ),
  617. Iterators.single((builder, params) -> builder.endArray())
  618. );
  619. });
  620. return Iterators.concat(
  621. Iterators.single(
  622. (builder, params) -> builder.startObject(indexRoutingTable.getIndex().getName()).startObject("shards")
  623. ),
  624. Iterators.flatMap(input, Function.identity()),
  625. Iterators.single((builder, params) -> builder.endObject().endObject())
  626. );
  627. },
  628. (builder, params) -> builder.endObject().endObject()
  629. ),
  630. // routing nodes
  631. chunkedSection(
  632. metrics.contains(Metric.ROUTING_NODES),
  633. (builder, params) -> builder.startObject("routing_nodes").startArray("unassigned"),
  634. getRoutingNodes().unassigned().iterator(),
  635. Iterators::single,
  636. (builder, params) -> builder.endArray() // no endObject() here, continued in next chunkedSection()
  637. ),
  638. chunkedSection(
  639. metrics.contains(Metric.ROUTING_NODES),
  640. (builder, params) -> builder.startObject("nodes"),
  641. getRoutingNodes().iterator(),
  642. routingNode -> Iterators.concat(
  643. ChunkedToXContentHelper.startArray(routingNode.nodeId() == null ? "null" : routingNode.nodeId()),
  644. routingNode.iterator(),
  645. ChunkedToXContentHelper.endArray()
  646. ),
  647. (builder, params) -> builder.endObject().endObject()
  648. ),
  649. // customs
  650. metrics.contains(Metric.CUSTOMS)
  651. ? Iterators.flatMap(
  652. customs.entrySet().iterator(),
  653. cursor -> ChunkedToXContentHelper.wrapWithObject(cursor.getKey(), cursor.getValue().toXContentChunked(outerParams))
  654. )
  655. : Collections.emptyIterator()
  656. );
  657. }
  658. public static Builder builder(ClusterName clusterName) {
  659. return new Builder(clusterName);
  660. }
  661. public static Builder builder(ClusterState state) {
  662. return new Builder(state);
  663. }
  664. public ClusterState copyAndUpdate(Consumer<Builder> updater) {
  665. var builder = builder(this);
  666. updater.accept(builder);
  667. return builder.build();
  668. }
  669. public ClusterState copyAndUpdateMetadata(Consumer<Metadata.Builder> updater) {
  670. return copyAndUpdate(builder -> builder.metadata(metadata().copyAndUpdate(updater)));
  671. }
  672. @SuppressForbidden(reason = "directly reading ClusterState#clusterFeatures")
  673. private static Map<String, Set<String>> getNodeFeatures(ClusterFeatures features) {
  674. return features.nodeFeatures();
  675. }
  676. public static class Builder {
  677. private ClusterState previous;
  678. private final ClusterName clusterName;
  679. private long version = 0;
  680. private String uuid = UNKNOWN_UUID;
  681. private Metadata metadata = Metadata.EMPTY_METADATA;
  682. private RoutingTable routingTable = RoutingTable.EMPTY_ROUTING_TABLE;
  683. private DiscoveryNodes nodes = DiscoveryNodes.EMPTY_NODES;
  684. private final Map<String, CompatibilityVersions> compatibilityVersions;
  685. private final Map<String, Set<String>> nodeFeatures;
  686. private ClusterBlocks blocks = ClusterBlocks.EMPTY_CLUSTER_BLOCK;
  687. private final ImmutableOpenMap.Builder<String, Custom> customs;
  688. private boolean fromDiff;
  689. public Builder(ClusterState state) {
  690. this.previous = state;
  691. this.clusterName = state.clusterName;
  692. this.version = state.version();
  693. this.uuid = state.stateUUID();
  694. this.nodes = state.nodes();
  695. this.compatibilityVersions = new HashMap<>(state.compatibilityVersions);
  696. this.nodeFeatures = new HashMap<>(getNodeFeatures(state.clusterFeatures()));
  697. this.routingTable = state.routingTable();
  698. this.metadata = state.metadata();
  699. this.blocks = state.blocks();
  700. this.customs = ImmutableOpenMap.builder(state.customs());
  701. this.fromDiff = false;
  702. }
  703. public Builder(ClusterName clusterName) {
  704. this.compatibilityVersions = new HashMap<>();
  705. this.nodeFeatures = new HashMap<>();
  706. customs = ImmutableOpenMap.builder();
  707. this.clusterName = clusterName;
  708. }
  709. public Builder nodes(DiscoveryNodes.Builder nodesBuilder) {
  710. return nodes(nodesBuilder.build());
  711. }
  712. public Builder nodes(DiscoveryNodes nodes) {
  713. this.nodes = nodes;
  714. return this;
  715. }
  716. public DiscoveryNodes nodes() {
  717. return nodes;
  718. }
  719. public Builder putCompatibilityVersions(
  720. String nodeId,
  721. TransportVersion transportVersion,
  722. Map<String, SystemIndexDescriptor.MappingsVersion> systemIndexMappingsVersions
  723. ) {
  724. return putCompatibilityVersions(
  725. nodeId,
  726. new CompatibilityVersions(Objects.requireNonNull(transportVersion, nodeId), systemIndexMappingsVersions)
  727. );
  728. }
  729. public Builder putCompatibilityVersions(String nodeId, CompatibilityVersions versions) {
  730. compatibilityVersions.put(nodeId, versions);
  731. return this;
  732. }
  733. public Builder nodeIdsToCompatibilityVersions(Map<String, CompatibilityVersions> versions) {
  734. versions.forEach((key, value) -> Objects.requireNonNull(value, key));
  735. // remove all versions not present in the new map
  736. this.compatibilityVersions.keySet().retainAll(versions.keySet());
  737. this.compatibilityVersions.putAll(versions);
  738. return this;
  739. }
  740. public Map<String, CompatibilityVersions> compatibilityVersions() {
  741. return Collections.unmodifiableMap(this.compatibilityVersions);
  742. }
  743. public Builder nodeFeatures(ClusterFeatures features) {
  744. this.nodeFeatures.clear();
  745. this.nodeFeatures.putAll(getNodeFeatures(features));
  746. return this;
  747. }
  748. public Builder nodeFeatures(Map<String, Set<String>> nodeFeatures) {
  749. this.nodeFeatures.clear();
  750. this.nodeFeatures.putAll(nodeFeatures);
  751. return this;
  752. }
  753. public Map<String, Set<String>> nodeFeatures() {
  754. return Collections.unmodifiableMap(this.nodeFeatures);
  755. }
  756. public Builder routingTable(RoutingTable.Builder routingTableBuilder) {
  757. return routingTable(routingTableBuilder.build());
  758. }
  759. public Builder routingTable(RoutingTable routingTable) {
  760. this.routingTable = routingTable;
  761. return this;
  762. }
  763. public Builder metadata(Metadata.Builder metadataBuilder) {
  764. return metadata(metadataBuilder.build());
  765. }
  766. public Builder metadata(Metadata metadata) {
  767. this.metadata = metadata;
  768. return this;
  769. }
  770. public Builder blocks(ClusterBlocks.Builder blocksBuilder) {
  771. return blocks(blocksBuilder.build());
  772. }
  773. public Builder blocks(ClusterBlocks blocks) {
  774. this.blocks = blocks;
  775. return this;
  776. }
  777. public Builder version(long version) {
  778. this.version = version;
  779. return this;
  780. }
  781. public Builder incrementVersion() {
  782. this.version = version + 1;
  783. this.uuid = UNKNOWN_UUID;
  784. return this;
  785. }
  786. public Builder stateUUID(String uuid) {
  787. this.uuid = uuid;
  788. return this;
  789. }
  790. public Builder putCustom(String type, Custom custom) {
  791. customs.put(type, Objects.requireNonNull(custom, type));
  792. return this;
  793. }
  794. public Builder removeCustom(String type) {
  795. customs.remove(type);
  796. return this;
  797. }
  798. public Builder customs(Map<String, Custom> customs) {
  799. customs.forEach((key, value) -> Objects.requireNonNull(value, key));
  800. this.customs.putAllFromMap(customs);
  801. return this;
  802. }
  803. // set previous cluster state that this builder is created from during diff application
  804. private Builder fromDiff(ClusterState previous) {
  805. this.fromDiff = true;
  806. this.previous = previous;
  807. return this;
  808. }
  809. public ClusterState build() {
  810. if (UNKNOWN_UUID.equals(uuid)) {
  811. uuid = UUIDs.randomBase64UUID();
  812. }
  813. final RoutingNodes routingNodes;
  814. if (previous != null && routingTable.indicesRouting() == previous.routingTable.indicesRouting() && nodes == previous.nodes) {
  815. // routing table contents and nodes haven't changed so we can try to reuse the previous state's routing nodes which are
  816. // expensive to compute
  817. routingNodes = previous.routingNodes;
  818. } else {
  819. routingNodes = null;
  820. }
  821. // ensure every node in the cluster has a feature set
  822. // nodes can be null in some tests
  823. if (nodes != null) {
  824. for (DiscoveryNode node : nodes) {
  825. nodeFeatures.putIfAbsent(node.getId(), Set.of());
  826. }
  827. }
  828. return new ClusterState(
  829. clusterName,
  830. version,
  831. uuid,
  832. metadata,
  833. routingTable,
  834. nodes,
  835. compatibilityVersions,
  836. new ClusterFeatures(nodeFeatures),
  837. blocks,
  838. customs.build(),
  839. fromDiff,
  840. routingNodes
  841. );
  842. }
  843. public static byte[] toBytes(ClusterState state) throws IOException {
  844. BytesStreamOutput os = new BytesStreamOutput();
  845. state.writeTo(os);
  846. return BytesReference.toBytes(os.bytes());
  847. }
  848. /**
  849. * @param data input bytes
  850. * @param localNode used to set the local node in the cluster state.
  851. */
  852. public static ClusterState fromBytes(byte[] data, DiscoveryNode localNode, NamedWriteableRegistry registry) throws IOException {
  853. StreamInput in = new NamedWriteableAwareStreamInput(StreamInput.wrap(data), registry);
  854. return readFrom(in, localNode);
  855. }
  856. }
  857. @Override
  858. public Diff<ClusterState> diff(ClusterState previousState) {
  859. return new ClusterStateDiff(previousState, this);
  860. }
  861. public static Diff<ClusterState> readDiffFrom(StreamInput in, DiscoveryNode localNode) throws IOException {
  862. return new ClusterStateDiff(in, localNode);
  863. }
  864. public static ClusterState readFrom(StreamInput in, DiscoveryNode localNode) throws IOException {
  865. ClusterName clusterName = new ClusterName(in);
  866. Builder builder = new Builder(clusterName);
  867. builder.version = in.readLong();
  868. builder.uuid = in.readString();
  869. builder.metadata = Metadata.readFrom(in);
  870. builder.routingTable = RoutingTable.readFrom(in);
  871. builder.nodes = DiscoveryNodes.readFrom(in, localNode);
  872. if (in.getTransportVersion().onOrAfter(TransportVersions.V_8_8_0)) {
  873. builder.nodeIdsToCompatibilityVersions(in.readMap(CompatibilityVersions::readVersion));
  874. } else {
  875. // this clusterstate is from a pre-8.8.0 node
  876. // infer the versions from discoverynodes for now
  877. // leave mappings versions empty
  878. builder.nodes()
  879. .getNodes()
  880. .values()
  881. .forEach(n -> builder.putCompatibilityVersions(n.getId(), inferTransportVersion(n), Map.of()));
  882. }
  883. if (in.getTransportVersion().onOrAfter(TransportVersions.CLUSTER_FEATURES_ADDED)) {
  884. builder.nodeFeatures(ClusterFeatures.readFrom(in));
  885. }
  886. builder.blocks = ClusterBlocks.readFrom(in);
  887. int customSize = in.readVInt();
  888. for (int i = 0; i < customSize; i++) {
  889. Custom customIndexMetadata = in.readNamedWriteable(Custom.class);
  890. builder.putCustom(customIndexMetadata.getWriteableName(), customIndexMetadata);
  891. }
  892. if (in.getTransportVersion().before(TransportVersions.V_8_0_0)) {
  893. in.readVInt(); // used to be minimumMasterNodesOnPublishingMaster, which was used in 7.x for BWC with 6.x
  894. }
  895. return builder.build();
  896. }
  897. /**
  898. * If the cluster state does not contain transport version information, this is the version
  899. * that is inferred for all nodes on version 8.8.0 or above.
  900. */
  901. public static final TransportVersion INFERRED_TRANSPORT_VERSION = TransportVersions.V_8_8_0;
  902. private static TransportVersion inferTransportVersion(DiscoveryNode node) {
  903. TransportVersion tv;
  904. if (node.getVersion().before(Version.V_8_8_0)) {
  905. // 1-to-1 mapping between Version and TransportVersion
  906. tv = TransportVersion.fromId(node.getPre811VersionId().getAsInt());
  907. } else {
  908. // use the lowest value it could be for now
  909. tv = INFERRED_TRANSPORT_VERSION;
  910. }
  911. return tv;
  912. }
  913. @Override
  914. public void writeTo(StreamOutput out) throws IOException {
  915. clusterName.writeTo(out);
  916. out.writeLong(version);
  917. out.writeString(stateUUID);
  918. metadata.writeTo(out);
  919. routingTable.writeTo(out);
  920. nodes.writeTo(out);
  921. if (out.getTransportVersion().onOrAfter(TransportVersions.V_8_8_0)) {
  922. out.writeMap(compatibilityVersions, (streamOutput, versions) -> versions.writeTo(streamOutput));
  923. }
  924. if (out.getTransportVersion().onOrAfter(TransportVersions.CLUSTER_FEATURES_ADDED)) {
  925. clusterFeatures.writeTo(out);
  926. }
  927. blocks.writeTo(out);
  928. VersionedNamedWriteable.writeVersionedWritables(out, customs);
  929. if (out.getTransportVersion().before(TransportVersions.V_8_0_0)) {
  930. out.writeVInt(-1); // used to be minimumMasterNodesOnPublishingMaster, which was used in 7.x for BWC with 6.x
  931. }
  932. }
  933. private static class ClusterStateDiff implements Diff<ClusterState> {
  934. private final long toVersion;
  935. private final String fromUuid;
  936. private final String toUuid;
  937. private final ClusterName clusterName;
  938. private final Diff<RoutingTable> routingTable;
  939. private final Diff<DiscoveryNodes> nodes;
  940. @Nullable
  941. private final Diff<Map<String, CompatibilityVersions>> versions;
  942. private final Diff<ClusterFeatures> features;
  943. private final Diff<Metadata> metadata;
  944. private final Diff<ClusterBlocks> blocks;
  945. private final Diff<Map<String, Custom>> customs;
  946. ClusterStateDiff(ClusterState before, ClusterState after) {
  947. fromUuid = before.stateUUID;
  948. toUuid = after.stateUUID;
  949. toVersion = after.version;
  950. clusterName = after.clusterName;
  951. routingTable = after.routingTable.diff(before.routingTable);
  952. nodes = after.nodes.diff(before.nodes);
  953. versions = DiffableUtils.diff(
  954. before.compatibilityVersions,
  955. after.compatibilityVersions,
  956. DiffableUtils.getStringKeySerializer(),
  957. COMPATIBILITY_VERSIONS_VALUE_SERIALIZER
  958. );
  959. features = after.clusterFeatures.diff(before.clusterFeatures);
  960. metadata = after.metadata.diff(before.metadata);
  961. blocks = after.blocks.diff(before.blocks);
  962. customs = DiffableUtils.diff(before.customs, after.customs, DiffableUtils.getStringKeySerializer(), CUSTOM_VALUE_SERIALIZER);
  963. }
  964. ClusterStateDiff(StreamInput in, DiscoveryNode localNode) throws IOException {
  965. clusterName = new ClusterName(in);
  966. fromUuid = in.readString();
  967. toUuid = in.readString();
  968. toVersion = in.readLong();
  969. routingTable = RoutingTable.readDiffFrom(in);
  970. nodes = DiscoveryNodes.readDiffFrom(in, localNode);
  971. if (in.getTransportVersion().onOrAfter(TransportVersions.V_8_8_0) && in.readBoolean()) {
  972. versions = DiffableUtils.readJdkMapDiff(
  973. in,
  974. DiffableUtils.getStringKeySerializer(),
  975. COMPATIBILITY_VERSIONS_VALUE_SERIALIZER
  976. );
  977. } else {
  978. versions = null; // infer at application time
  979. }
  980. if (in.getTransportVersion().onOrAfter(TransportVersions.CLUSTER_FEATURES_ADDED)) {
  981. features = ClusterFeatures.readDiffFrom(in);
  982. } else {
  983. features = null; // fill in when nodes re-register with a master that understands features
  984. }
  985. metadata = Metadata.readDiffFrom(in);
  986. blocks = ClusterBlocks.readDiffFrom(in);
  987. customs = DiffableUtils.readJdkMapDiff(in, DiffableUtils.getStringKeySerializer(), CUSTOM_VALUE_SERIALIZER);
  988. if (in.getTransportVersion().before(TransportVersions.V_8_0_0)) {
  989. in.readVInt(); // used to be minimumMasterNodesOnPublishingMaster, which was used in 7.x for BWC with 6.x
  990. }
  991. }
  992. @Override
  993. public void writeTo(StreamOutput out) throws IOException {
  994. clusterName.writeTo(out);
  995. out.writeString(fromUuid);
  996. out.writeString(toUuid);
  997. out.writeLong(toVersion);
  998. routingTable.writeTo(out);
  999. nodes.writeTo(out);
  1000. if (out.getTransportVersion().onOrAfter(TransportVersions.V_8_8_0)) {
  1001. out.writeOptionalWriteable(versions);
  1002. }
  1003. if (out.getTransportVersion().onOrAfter(TransportVersions.CLUSTER_FEATURES_ADDED)) {
  1004. features.writeTo(out);
  1005. }
  1006. metadata.writeTo(out);
  1007. blocks.writeTo(out);
  1008. customs.writeTo(out);
  1009. if (out.getTransportVersion().before(TransportVersions.V_8_0_0)) {
  1010. out.writeVInt(-1); // used to be minimumMasterNodesOnPublishingMaster, which was used in 7.x for BWC with 6.x
  1011. }
  1012. }
  1013. @Override
  1014. public ClusterState apply(ClusterState state) {
  1015. Builder builder = new Builder(clusterName);
  1016. if (toUuid.equals(state.stateUUID)) {
  1017. // no need to read the rest - cluster state didn't change
  1018. return state;
  1019. }
  1020. if (fromUuid.equals(state.stateUUID) == false) {
  1021. throw new IncompatibleClusterStateVersionException(state.version, state.stateUUID, toVersion, fromUuid);
  1022. }
  1023. builder.stateUUID(toUuid);
  1024. builder.version(toVersion);
  1025. builder.routingTable(routingTable.apply(state.routingTable));
  1026. builder.nodes(nodes.apply(state.nodes));
  1027. if (versions != null) {
  1028. builder.nodeIdsToCompatibilityVersions(this.versions.apply(state.compatibilityVersions));
  1029. } else {
  1030. // infer the versions from discoverynodes for now
  1031. // leave mappings versions empty
  1032. builder.nodes()
  1033. .getNodes()
  1034. .values()
  1035. .forEach(n -> builder.putCompatibilityVersions(n.getId(), inferTransportVersion(n), Map.of()));
  1036. }
  1037. if (features != null) {
  1038. builder.nodeFeatures(this.features.apply(state.clusterFeatures));
  1039. }
  1040. builder.metadata(metadata.apply(state.metadata));
  1041. builder.blocks(blocks.apply(state.blocks));
  1042. builder.customs(customs.apply(state.customs));
  1043. builder.fromDiff(state);
  1044. return builder.build();
  1045. }
  1046. }
  1047. }