You are viewing a plain text version of this content. The canonical link for it is here.
Posted to pr@cassandra.apache.org by GitBox <gi...@apache.org> on 2020/09/25 17:26:51 UTC
[GitHub] [cassandra] ifesdjeen opened a new pull request #759: Improve machinery for testing bootstrap and range movements
ifesdjeen opened a new pull request #759:
URL: https://github.com/apache/cassandra/pull/759
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
[GitHub] [cassandra] ifesdjeen commented on a change in pull request #759: Improve machinery for testing bootstrap and range movements
Posted by GitBox <gi...@apache.org>.
ifesdjeen commented on a change in pull request #759:
URL: https://github.com/apache/cassandra/pull/759#discussion_r508273004
##########
File path: test/distributed/org/apache/cassandra/distributed/action/GossipHelper.java
##########
@@ -0,0 +1,431 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.distributed.action;
+
+import java.io.IOException;
+import java.io.Serializable;
+import java.net.InetSocketAddress;
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.TimeUnit;
+import java.util.stream.Stream;
+
+import net.openhft.chronicle.core.util.SerializableBiFunction;
+import org.apache.cassandra.db.SystemKeyspace;
+import org.apache.cassandra.dht.IPartitioner;
+import org.apache.cassandra.dht.Token;
+import org.apache.cassandra.distributed.api.IInstance;
+import org.apache.cassandra.distributed.api.IInvokableInstance;
+import org.apache.cassandra.distributed.api.IIsolatedExecutor;
+import org.apache.cassandra.distributed.impl.Instance;
+import org.apache.cassandra.distributed.shared.VersionedApplicationState;
+import org.apache.cassandra.gms.ApplicationState;
+import org.apache.cassandra.gms.EndpointState;
+import org.apache.cassandra.gms.Gossiper;
+import org.apache.cassandra.gms.VersionedValue;
+import org.apache.cassandra.io.util.DataInputBuffer;
+import org.apache.cassandra.io.util.DataOutputBuffer;
+import org.apache.cassandra.locator.InetAddressAndPort;
+import org.apache.cassandra.locator.TokenMetadata;
+import org.apache.cassandra.net.MessagingService;
+import org.apache.cassandra.schema.MigrationManager;
+import org.apache.cassandra.service.PendingRangeCalculatorService;
+import org.apache.cassandra.service.StorageService;
+import org.apache.cassandra.utils.FBUtilities;
+
+import static org.apache.cassandra.distributed.impl.DistributedTestSnitch.toCassandraInetAddressAndPort;
+
+public class GossipHelper
+{
+ public static InstanceAction statusToBootstrap(IInvokableInstance newNode)
+ {
+ return (instance) ->
+ {
+ changeGossipState(instance,
+ newNode,
+ Arrays.asList(tokens(newNode),
+ statusBootstrapping(newNode),
+ statusWithPortBootstrapping(newNode)));
+ };
+ }
+
+ public static InstanceAction statusToNormal(IInvokableInstance peer)
+ {
+ return (target) ->
+ {
+ changeGossipState(target,
+ peer,
+ Arrays.asList(tokens(peer),
+ statusNormal(peer),
+ releaseVersion(peer),
+ statusWithPortNormal(peer)));
+ };
+ }
+
+ /**
+ * This method is unsafe and should be used _only_ when gossip is not used or available: it creates versioned values on the
+ * target instance, which means Gossip versioning gets out of sync. Use a safe couterpart at all times when performing _any_
+ * ring movement operations _or_ if Gossip is used.
+ */
+ public static InstanceAction unsafeStatusToNormal(IInstance peer)
+ {
+ return (target) ->
+ {
+ changeGossipState(target,
+ peer,
+ Arrays.asList(unsafeVersionedToken(target,
+ ApplicationState.TOKENS,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).tokens(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeVersionedToken(target,
+ ApplicationState.STATUS,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeVersionedToken(target,
+ ApplicationState.STATUS_WITH_PORT,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeReleaseVersion(target,
+ peer.config().getString("partitioner"),
+ peer.getReleaseVersionString())));
+ };
+ }
+
+ public static InstanceAction statusToLeaving(IInvokableInstance newNode)
+ {
+ return (instance) -> {
+ changeGossipState(instance,
+ newNode,
+ Arrays.asList(tokens(newNode),
+ statusLeaving(newNode),
+ statusWithPortLeaving(newNode)));
+ };
+ }
+
+ public static InstanceAction bootstrap()
+ {
+ return new BootstrapAction();
+ }
+
+ public static InstanceAction bootstrap(boolean joinRing, Duration waitForBootstrap, Duration waitForSchema)
+ {
+ return new BootstrapAction(joinRing, waitForBootstrap, waitForSchema);
+ }
+
+ public static InstanceAction disseminateGossipState(IInvokableInstance newNode)
+ {
+ return new DisseminateGossipState(newNode);
+ }
+
+ public static InstanceAction pullSchemaFrom(IInvokableInstance pullFrom)
+ {
+ return new PullSchemaFrom(pullFrom);
+ }
+
+ private static InstanceAction disableBinary()
+ {
+ return (instance) -> {
+ instance.runOnInstance(StorageService.instance::stopNativeTransport);
+ };
+ }
+
+ private static class DisseminateGossipState implements InstanceAction
+ {
+ final Map<InetSocketAddress, byte[]> gossipState;
+
+ public DisseminateGossipState(IInvokableInstance... from)
+ {
+ gossipState = new HashMap<>();
+ for (IInvokableInstance node : from)
+ {
+ byte[] epBytes = node.callsOnInstance(() -> {
+ EndpointState epState = Gossiper.instance.getEndpointStateForEndpoint(FBUtilities.getBroadcastAddressAndPort());
+ return toBytes(epState);
+ }).call();
+ gossipState.put(node.broadcastAddress(), epBytes);
+ }
+ }
+
+ public void accept(IInvokableInstance instance)
+ {
+ instance.appliesOnInstance((IIsolatedExecutor.SerializableFunction<Map<InetSocketAddress, byte[]>, Void>)
+ (map) -> {
+ Map<InetAddressAndPort, EndpointState> newState = new HashMap<>();
+ for (Map.Entry<InetSocketAddress, byte[]> e : map.entrySet())
+ newState.put(toCassandraInetAddressAndPort(e.getKey()), fromBytes(e.getValue()));
+
+ Gossiper.runInGossipStageBlocking(() -> {
+ Gossiper.instance.applyStateLocally(newState);
+ });
+ return null;
+ }).apply(gossipState);
+ }
+ }
+
+ public static byte[] toBytes(EndpointState epState)
+ {
+ try (DataOutputBuffer out = new DataOutputBuffer(1024))
+ {
+ EndpointState.serializer.serialize(epState, out, MessagingService.current_version);
+ return out.toByteArray();
+ }
+ catch (IOException e)
+ {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public static EndpointState fromBytes(byte[] bytes)
+ {
+ try (DataInputBuffer in = new DataInputBuffer(bytes))
+ {
+ return EndpointState.serializer.deserialize(in, MessagingService.current_version);
+ }
+ catch (Throwable t)
+ {
+ throw new RuntimeException(t);
+ }
+ }
+
+ private static class PullSchemaFrom implements InstanceAction
+ {
+ final InetSocketAddress pullFrom;
+
+ public PullSchemaFrom(IInvokableInstance pullFrom)
+ {
+ this.pullFrom = pullFrom.broadcastAddress();;
+ }
+
+ public void accept(IInvokableInstance pullTo)
+ {
+ pullTo.acceptsOnInstance((InetSocketAddress pullFrom) -> {
+ InetAddressAndPort endpoint = toCassandraInetAddressAndPort(pullFrom);
+ EndpointState state = Gossiper.instance.getEndpointStateForEndpoint(endpoint);
+ MigrationManager.scheduleSchemaPull(endpoint, state);
+ MigrationManager.waitUntilReadyForBootstrap();
+ }).accept(pullFrom);
+ }
+ }
+
+ private static class BootstrapAction implements InstanceAction, Serializable
+ {
+ private final boolean joinRing;
+ private final Duration waitForBootstrap;
+ private final Duration waitForSchema;
+
+ public BootstrapAction()
+ {
+ this(true, Duration.ofMinutes(10), Duration.ofSeconds(10));
+ }
+
+ public BootstrapAction(boolean joinRing, Duration waitForBootstrap, Duration waitForSchema)
+ {
+ this.joinRing = joinRing;
+ this.waitForBootstrap = waitForBootstrap;
+ this.waitForSchema = waitForSchema;
+ }
+
+ public void accept(IInvokableInstance instance)
+ {
+ instance.appliesOnInstance((String partitionerString, String tokenString) -> {
+ IPartitioner partitioner = FBUtilities.newPartitioner(partitionerString);
+ List<Token> tokens = Collections.singletonList(partitioner.getTokenFactory().fromString(tokenString));
+ try
+ {
+ SystemKeyspace.setBootstrapState(SystemKeyspace.BootstrapState.IN_PROGRESS);
+ StorageService.instance.waitForSchema((int) waitForSchema.toMillis());
+ PendingRangeCalculatorService.instance.blockUntilFinished();
+ StorageService.instance.startBootstrap(tokens).get(waitForBootstrap.toMillis(), TimeUnit.MILLISECONDS);
+ StorageService.instance.setUpDistributedSystemKeyspaces();
+ if (joinRing)
+ StorageService.instance.finishJoiningRing(true, tokens);
+ }
+ catch (Throwable t)
+ {
+ throw new RuntimeException(t);
+ }
+
+ return null;
+ }).apply(instance.config().getString("partitioner"), instance.config().getString("initial_token"));
+ }
+ }
+
+ public static InstanceAction decomission()
+ {
+ return (target) -> {
+ target.runOnInstance(() -> {
+ try
+ {
+ StorageService.instance.decommission(false);
+ }
+ catch (InterruptedException e)
+ {
+ throw new RuntimeException();
+ }
+ });
+ };
+ }
+
+
+ public static VersionedApplicationState tokens(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.TOKENS, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).tokens(tokens));
+ }
+
+ public static VersionedApplicationState unsafeReleaseVersion(IInvokableInstance instance, String partitionerStr, String releaseVersionStr)
+ {
+ return instance.appliesOnInstance((String partitionerString, String releaseVersion) -> {
+ IPartitioner partitioner = FBUtilities.newPartitioner(partitionerString);
+ VersionedValue versionedValue = new VersionedValue.VersionedValueFactory(partitioner).releaseVersion(releaseVersion);
+ return new VersionedApplicationState(ApplicationState.RELEASE_VERSION.ordinal(), versionedValue.value, versionedValue.version);
+ }).apply(partitionerStr, releaseVersionStr);
+ }
+
+ public static VersionedApplicationState releaseVersion(IInvokableInstance instance)
+ {
+ return unsafeReleaseVersion(instance, instance.config().getString("partitioner"), instance.getReleaseVersionString());
+ }
+
+ public static VersionedApplicationState statusNormal(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens));
+ }
+
+ public static VersionedApplicationState statusWithPortNormal(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS_WITH_PORT, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens));
+ }
+
+ public static VersionedApplicationState statusBootstrapping(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).bootstrapping(tokens));
+ }
+
+ public static VersionedApplicationState statusWithPortBootstrapping(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS_WITH_PORT, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).bootstrapping(tokens));
+ }
+
+ public static VersionedApplicationState statusLeaving(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).leaving(tokens));
+ }
+
+ public static VersionedApplicationState statusWithPortLeaving(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS_WITH_PORT, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).leaving(tokens));
+ }
+
+ public static VersionedValue toVersionedValue(VersionedApplicationState vv)
+ {
+ return VersionedValue.unsafeMakeVersionedValue(vv.value, vv.version);
+ }
+
+ public static ApplicationState toApplicationState(VersionedApplicationState vv)
+ {
+ return ApplicationState.values()[vv.applicationState];
+ }
+
+ public static VersionedApplicationState unsafeVersionedToken(IInvokableInstance instance,
+ ApplicationState applicationState,
+ SerializableBiFunction<IPartitioner, Collection<Token>, VersionedValue> supplier,
+ String partitionerStr, String initialTokenStr)
+ {
+ return instance.appliesOnInstance((String partitionerString, String tokenString) -> {
+ IPartitioner partitioner = FBUtilities.newPartitioner(partitionerString);
+ Token token = partitioner.getTokenFactory().fromString(tokenString);
+
+ VersionedValue versionedValue = supplier.apply(partitioner, Collections.singleton(token));
+ return new VersionedApplicationState(applicationState.ordinal(), versionedValue.value, versionedValue.version);
+ }).apply(partitionerStr, initialTokenStr);
+ }
+
+ public static VersionedApplicationState versionedToken(IInvokableInstance instance, ApplicationState applicationState, SerializableBiFunction<IPartitioner, Collection<Token>, VersionedValue> supplier)
+ {
+ return unsafeVersionedToken(instance, applicationState, supplier, instance.config().getString("partitioner"), instance.config().getString("initial_token"));
+ }
+
+ public void removeFromRing(IInstance peer)
+ {
+ InetAddressAndPort endpoint = toCassandraInetAddressAndPort(peer.broadcastAddress());
+
+ TokenMetadata tokenMetadata = StorageService.instance.getTokenMetadata();
+ tokenMetadata.removeEndpoint(endpoint);
+ Collection<Token> tokens = tokenMetadata.getTokens(endpoint);
+ if (!tokens.isEmpty())
+ tokenMetadata.removeBootstrapTokens(tokens);
+
+ Gossiper.runInGossipStageBlocking(() -> Gossiper.instance.unsafeAnulEndpoint(endpoint));
+
+ SystemKeyspace.removeEndpoint(endpoint);
+ PendingRangeCalculatorService.instance.update();
+ PendingRangeCalculatorService.instance.blockUntilFinished();
+ }
+
+ public static void changeGossipState(Stream<IInvokableInstance> targets, Instance peer, List<VersionedApplicationState> newState)
+ {
+ targets.forEach((instance) -> {
+ changeGossipState(instance, peer, newState);
+ });
+ }
+
+ /**
+ * Changes gossip state of the `peer` on `target`
+ */
+ public static void changeGossipState(IInvokableInstance target, IInstance peer, List<VersionedApplicationState> newState)
+ {
+ int version = peer.isShutdown() ? MessagingService.current_version : peer.getMessagingVersion();
+
+ target.appliesOnInstance((InetSocketAddress addr, UUID hostId, Integer messagingVersion) -> {
+ InetAddressAndPort endpoint = toCassandraInetAddressAndPort(addr);
+ StorageService storageService = StorageService.instance;
+
+ Gossiper.runInGossipStageBlocking(() -> {
+ EndpointState state = Gossiper.instance.getEndpointStateForEndpoint(endpoint);
+ if (state == null)
+ {
+ Gossiper.instance.initializeNodeUnsafe(endpoint, hostId, 1);
Review comment:
Since i've switched to use net_version below, I think it should be ok here.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
[GitHub] [cassandra] ifesdjeen commented on a change in pull request #759: Improve machinery for testing bootstrap and range movements
Posted by GitBox <gi...@apache.org>.
ifesdjeen commented on a change in pull request #759:
URL: https://github.com/apache/cassandra/pull/759#discussion_r507711284
##########
File path: test/distributed/org/apache/cassandra/distributed/impl/Instance.java
##########
@@ -443,25 +457,31 @@ public void startup(ICluster cluster)
StorageService.instance.registerDaemon(CassandraDaemon.getInstanceForTesting());
if (config.has(GOSSIP))
{
+ MigrationManager.setUptimeFn(() -> System.currentTimeMillis() - startedAt);
Review comment:
Since this is not production code, I don't think this is strictly necessary, but why not. Thanks for spotting, added this change.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
[GitHub] [cassandra] dcapwell commented on a change in pull request #759: Improve machinery for testing bootstrap and range movements
Posted by GitBox <gi...@apache.org>.
dcapwell commented on a change in pull request #759:
URL: https://github.com/apache/cassandra/pull/759#discussion_r509456259
##########
File path: test/distributed/org/apache/cassandra/distributed/action/GossipHelper.java
##########
@@ -0,0 +1,455 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.distributed.action;
+
+import java.io.IOException;
+import java.io.Serializable;
+import java.net.InetSocketAddress;
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.TimeUnit;
+import java.util.function.Supplier;
+
+import org.apache.cassandra.db.SystemKeyspace;
+import org.apache.cassandra.dht.IPartitioner;
+import org.apache.cassandra.dht.Token;
+import org.apache.cassandra.distributed.api.IInstance;
+import org.apache.cassandra.distributed.api.IInvokableInstance;
+import org.apache.cassandra.distributed.api.IIsolatedExecutor;
+import org.apache.cassandra.distributed.shared.VersionedApplicationState;
+import org.apache.cassandra.gms.ApplicationState;
+import org.apache.cassandra.gms.EndpointState;
+import org.apache.cassandra.gms.Gossiper;
+import org.apache.cassandra.gms.VersionedValue;
+import org.apache.cassandra.io.util.DataInputBuffer;
+import org.apache.cassandra.io.util.DataOutputBuffer;
+import org.apache.cassandra.locator.InetAddressAndPort;
+import org.apache.cassandra.net.MessagingService;
+import org.apache.cassandra.schema.MigrationManager;
+import org.apache.cassandra.service.PendingRangeCalculatorService;
+import org.apache.cassandra.service.StorageService;
+import org.apache.cassandra.utils.FBUtilities;
+
+import static org.apache.cassandra.distributed.impl.DistributedTestSnitch.toCassandraInetAddressAndPort;
+
+public class GossipHelper
+{
+ public static InstanceAction statusToBootstrap(IInvokableInstance newNode)
+ {
+ return (instance) ->
+ {
+ changeGossipState(instance,
+ newNode,
+ Arrays.asList(tokens(newNode),
+ statusBootstrapping(newNode),
+ statusWithPortBootstrapping(newNode)));
+ };
+ }
+
+ public static InstanceAction statusToNormal(IInvokableInstance peer)
+ {
+ return (target) ->
+ {
+ changeGossipState(target,
+ peer,
+ Arrays.asList(tokens(peer),
+ statusNormal(peer),
+ releaseVersion(peer),
+ netVersion(peer),
+ statusWithPortNormal(peer)));
+ };
+ }
+
+ /**
+ * This method is unsafe and should be used _only_ when gossip is not used or available: it creates versioned values on the
+ * target instance, which means Gossip versioning gets out of sync. Use a safe couterpart at all times when performing _any_
+ * ring movement operations _or_ if Gossip is used.
+ */
+ public static void unsafeStatusToNormal(IInvokableInstance target, IInstance peer)
+ {
+ int messagingVersion = peer.getMessagingVersion();
+ changeGossipState(target,
+ peer,
+ Arrays.asList(unsafeVersionedValue(target,
+ ApplicationState.TOKENS,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).tokens(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeVersionedValue(target,
+ ApplicationState.STATUS,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeVersionedValue(target,
+ ApplicationState.STATUS_WITH_PORT,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeVersionedValue(target,
+ ApplicationState.NET_VERSION,
+ (partitioner) -> new VersionedValue.VersionedValueFactory(partitioner).networkVersion(messagingVersion),
+ peer.config().getString("partitioner")),
+ unsafeReleaseVersion(target,
+ peer.config().getString("partitioner"),
+ peer.getReleaseVersionString())));
+ }
+
+ public static InstanceAction statusToLeaving(IInvokableInstance newNode)
+ {
+ return (instance) -> {
+ changeGossipState(instance,
+ newNode,
+ Arrays.asList(tokens(newNode),
+ statusLeaving(newNode),
+ statusWithPortLeaving(newNode)));
+ };
+ }
+
+ public static InstanceAction bootstrap()
+ {
+ return new BootstrapAction();
+ }
+
+ public static InstanceAction bootstrap(boolean joinRing, Duration waitForBootstrap, Duration waitForSchema)
+ {
+ return new BootstrapAction(joinRing, waitForBootstrap, waitForSchema);
+ }
+
+ public static InstanceAction disseminateGossipState(IInvokableInstance newNode)
+ {
+ return new DisseminateGossipState(newNode);
+ }
+
+ public static InstanceAction pullSchemaFrom(IInvokableInstance pullFrom)
+ {
+ return new PullSchemaFrom(pullFrom);
+ }
+
+ private static InstanceAction disableBinary()
+ {
+ return (instance) -> instance.nodetoolResult("disablebinary").asserts().success();
+ }
+
+ private static class DisseminateGossipState implements InstanceAction
+ {
+ final Map<InetSocketAddress, byte[]> gossipState;
+
+ public DisseminateGossipState(IInvokableInstance... from)
+ {
+ gossipState = new HashMap<>();
+ for (IInvokableInstance node : from)
+ {
+ byte[] epBytes = node.callsOnInstance(() -> {
+ EndpointState epState = Gossiper.instance.getEndpointStateForEndpoint(FBUtilities.getBroadcastAddressAndPort());
+ return toBytes(epState);
+ }).call();
+ gossipState.put(node.broadcastAddress(), epBytes);
+ }
+ }
+
+ public void accept(IInvokableInstance instance)
+ {
+ instance.appliesOnInstance((IIsolatedExecutor.SerializableFunction<Map<InetSocketAddress, byte[]>, Void>)
+ (map) -> {
+ Map<InetAddressAndPort, EndpointState> newState = new HashMap<>();
+ for (Map.Entry<InetSocketAddress, byte[]> e : map.entrySet())
+ newState.put(toCassandraInetAddressAndPort(e.getKey()), fromBytes(e.getValue()));
+
+ Gossiper.runInGossipStageBlocking(() -> {
+ Gossiper.instance.applyStateLocally(newState);
+ });
+ return null;
+ }).apply(gossipState);
+ }
+ }
+
+ private static byte[] toBytes(EndpointState epState)
+ {
+ try (DataOutputBuffer out = new DataOutputBuffer(1024))
+ {
+ EndpointState.serializer.serialize(epState, out, MessagingService.current_version);
+ return out.toByteArray();
+ }
+ catch (IOException e)
+ {
+ throw new RuntimeException(e);
+ }
+ }
+
+ private static EndpointState fromBytes(byte[] bytes)
+ {
+ try (DataInputBuffer in = new DataInputBuffer(bytes))
+ {
+ return EndpointState.serializer.deserialize(in, MessagingService.current_version);
+ }
+ catch (Throwable t)
+ {
+ throw new RuntimeException(t);
+ }
+ }
+
+ private static class PullSchemaFrom implements InstanceAction
+ {
+ final InetSocketAddress pullFrom;
+
+ public PullSchemaFrom(IInvokableInstance pullFrom)
+ {
+ this.pullFrom = pullFrom.broadcastAddress();;
+ }
+
+ public void accept(IInvokableInstance pullTo)
+ {
+ pullTo.acceptsOnInstance((InetSocketAddress pullFrom) -> {
+ InetAddressAndPort endpoint = toCassandraInetAddressAndPort(pullFrom);
+ EndpointState state = Gossiper.instance.getEndpointStateForEndpoint(endpoint);
+ MigrationManager.scheduleSchemaPull(endpoint, state);
+ MigrationManager.waitUntilReadyForBootstrap();
+ }).accept(pullFrom);
+ }
+ }
+
+ private static class BootstrapAction implements InstanceAction, Serializable
+ {
+ private final boolean joinRing;
+ private final Duration waitForBootstrap;
+ private final Duration waitForSchema;
+
+ public BootstrapAction()
+ {
+ this(true, Duration.ofMinutes(10), Duration.ofSeconds(10));
+ }
+
+ public BootstrapAction(boolean joinRing, Duration waitForBootstrap, Duration waitForSchema)
+ {
+ this.joinRing = joinRing;
+ this.waitForBootstrap = waitForBootstrap;
+ this.waitForSchema = waitForSchema;
+ }
+
+ public void accept(IInvokableInstance instance)
+ {
+ instance.appliesOnInstance((String partitionerString, String tokenString) -> {
+ IPartitioner partitioner = FBUtilities.newPartitioner(partitionerString);
+ List<Token> tokens = Collections.singletonList(partitioner.getTokenFactory().fromString(tokenString));
+ try
+ {
+ assert StorageService.instance.prepareForBootstrap(waitForSchema.toMillis()).size() == 0;
Review comment:
so not supporting replace; k
##########
File path: src/java/org/apache/cassandra/service/StorageService.java
##########
@@ -1529,6 +1462,96 @@ private void setMode(Mode m, String msg, boolean log)
logger.debug(logMsg);
}
+ @VisibleForTesting
+ public Collection<InetAddressAndPort> prepareForBootstrap(long schemaDelay)
Review comment:
for me: I walked line by line against the branch this got refactored from and looks identical (minus schemaDelay renamed from delay).
##########
File path: test/distributed/org/apache/cassandra/distributed/action/GossipHelper.java
##########
@@ -0,0 +1,455 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.distributed.action;
+
+import java.io.IOException;
+import java.io.Serializable;
+import java.net.InetSocketAddress;
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.TimeUnit;
+import java.util.function.Supplier;
+
+import org.apache.cassandra.db.SystemKeyspace;
+import org.apache.cassandra.dht.IPartitioner;
+import org.apache.cassandra.dht.Token;
+import org.apache.cassandra.distributed.api.IInstance;
+import org.apache.cassandra.distributed.api.IInvokableInstance;
+import org.apache.cassandra.distributed.api.IIsolatedExecutor;
+import org.apache.cassandra.distributed.shared.VersionedApplicationState;
+import org.apache.cassandra.gms.ApplicationState;
+import org.apache.cassandra.gms.EndpointState;
+import org.apache.cassandra.gms.Gossiper;
+import org.apache.cassandra.gms.VersionedValue;
+import org.apache.cassandra.io.util.DataInputBuffer;
+import org.apache.cassandra.io.util.DataOutputBuffer;
+import org.apache.cassandra.locator.InetAddressAndPort;
+import org.apache.cassandra.net.MessagingService;
+import org.apache.cassandra.schema.MigrationManager;
+import org.apache.cassandra.service.PendingRangeCalculatorService;
+import org.apache.cassandra.service.StorageService;
+import org.apache.cassandra.utils.FBUtilities;
+
+import static org.apache.cassandra.distributed.impl.DistributedTestSnitch.toCassandraInetAddressAndPort;
+
+public class GossipHelper
+{
+ public static InstanceAction statusToBootstrap(IInvokableInstance newNode)
+ {
+ return (instance) ->
+ {
+ changeGossipState(instance,
+ newNode,
+ Arrays.asList(tokens(newNode),
+ statusBootstrapping(newNode),
+ statusWithPortBootstrapping(newNode)));
+ };
+ }
+
+ public static InstanceAction statusToNormal(IInvokableInstance peer)
+ {
+ return (target) ->
+ {
+ changeGossipState(target,
+ peer,
+ Arrays.asList(tokens(peer),
+ statusNormal(peer),
+ releaseVersion(peer),
+ netVersion(peer),
+ statusWithPortNormal(peer)));
+ };
+ }
+
+ /**
+ * This method is unsafe and should be used _only_ when gossip is not used or available: it creates versioned values on the
+ * target instance, which means Gossip versioning gets out of sync. Use a safe couterpart at all times when performing _any_
+ * ring movement operations _or_ if Gossip is used.
+ */
+ public static void unsafeStatusToNormal(IInvokableInstance target, IInstance peer)
+ {
+ int messagingVersion = peer.getMessagingVersion();
+ changeGossipState(target,
+ peer,
+ Arrays.asList(unsafeVersionedValue(target,
+ ApplicationState.TOKENS,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).tokens(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeVersionedValue(target,
+ ApplicationState.STATUS,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeVersionedValue(target,
+ ApplicationState.STATUS_WITH_PORT,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeVersionedValue(target,
+ ApplicationState.NET_VERSION,
+ (partitioner) -> new VersionedValue.VersionedValueFactory(partitioner).networkVersion(messagingVersion),
+ peer.config().getString("partitioner")),
+ unsafeReleaseVersion(target,
+ peer.config().getString("partitioner"),
+ peer.getReleaseVersionString())));
+ }
+
+ public static InstanceAction statusToLeaving(IInvokableInstance newNode)
+ {
+ return (instance) -> {
+ changeGossipState(instance,
+ newNode,
+ Arrays.asList(tokens(newNode),
+ statusLeaving(newNode),
+ statusWithPortLeaving(newNode)));
+ };
+ }
+
+ public static InstanceAction bootstrap()
+ {
+ return new BootstrapAction();
+ }
+
+ public static InstanceAction bootstrap(boolean joinRing, Duration waitForBootstrap, Duration waitForSchema)
+ {
+ return new BootstrapAction(joinRing, waitForBootstrap, waitForSchema);
+ }
+
+ public static InstanceAction disseminateGossipState(IInvokableInstance newNode)
+ {
+ return new DisseminateGossipState(newNode);
+ }
+
+ public static InstanceAction pullSchemaFrom(IInvokableInstance pullFrom)
+ {
+ return new PullSchemaFrom(pullFrom);
+ }
+
+ private static InstanceAction disableBinary()
+ {
+ return (instance) -> instance.nodetoolResult("disablebinary").asserts().success();
+ }
+
+ private static class DisseminateGossipState implements InstanceAction
+ {
+ final Map<InetSocketAddress, byte[]> gossipState;
+
+ public DisseminateGossipState(IInvokableInstance... from)
+ {
+ gossipState = new HashMap<>();
+ for (IInvokableInstance node : from)
+ {
+ byte[] epBytes = node.callsOnInstance(() -> {
+ EndpointState epState = Gossiper.instance.getEndpointStateForEndpoint(FBUtilities.getBroadcastAddressAndPort());
+ return toBytes(epState);
+ }).call();
+ gossipState.put(node.broadcastAddress(), epBytes);
+ }
+ }
+
+ public void accept(IInvokableInstance instance)
+ {
+ instance.appliesOnInstance((IIsolatedExecutor.SerializableFunction<Map<InetSocketAddress, byte[]>, Void>)
+ (map) -> {
+ Map<InetAddressAndPort, EndpointState> newState = new HashMap<>();
+ for (Map.Entry<InetSocketAddress, byte[]> e : map.entrySet())
+ newState.put(toCassandraInetAddressAndPort(e.getKey()), fromBytes(e.getValue()));
+
+ Gossiper.runInGossipStageBlocking(() -> {
+ Gossiper.instance.applyStateLocally(newState);
+ });
+ return null;
+ }).apply(gossipState);
+ }
+ }
+
+ private static byte[] toBytes(EndpointState epState)
+ {
+ try (DataOutputBuffer out = new DataOutputBuffer(1024))
+ {
+ EndpointState.serializer.serialize(epState, out, MessagingService.current_version);
+ return out.toByteArray();
+ }
+ catch (IOException e)
+ {
+ throw new RuntimeException(e);
+ }
+ }
+
+ private static EndpointState fromBytes(byte[] bytes)
+ {
+ try (DataInputBuffer in = new DataInputBuffer(bytes))
+ {
+ return EndpointState.serializer.deserialize(in, MessagingService.current_version);
+ }
+ catch (Throwable t)
+ {
+ throw new RuntimeException(t);
+ }
+ }
+
+ private static class PullSchemaFrom implements InstanceAction
+ {
+ final InetSocketAddress pullFrom;
+
+ public PullSchemaFrom(IInvokableInstance pullFrom)
+ {
+ this.pullFrom = pullFrom.broadcastAddress();;
+ }
+
+ public void accept(IInvokableInstance pullTo)
+ {
+ pullTo.acceptsOnInstance((InetSocketAddress pullFrom) -> {
+ InetAddressAndPort endpoint = toCassandraInetAddressAndPort(pullFrom);
+ EndpointState state = Gossiper.instance.getEndpointStateForEndpoint(endpoint);
+ MigrationManager.scheduleSchemaPull(endpoint, state);
+ MigrationManager.waitUntilReadyForBootstrap();
+ }).accept(pullFrom);
+ }
+ }
+
+ private static class BootstrapAction implements InstanceAction, Serializable
+ {
+ private final boolean joinRing;
+ private final Duration waitForBootstrap;
+ private final Duration waitForSchema;
+
+ public BootstrapAction()
+ {
+ this(true, Duration.ofMinutes(10), Duration.ofSeconds(10));
+ }
+
+ public BootstrapAction(boolean joinRing, Duration waitForBootstrap, Duration waitForSchema)
+ {
+ this.joinRing = joinRing;
+ this.waitForBootstrap = waitForBootstrap;
+ this.waitForSchema = waitForSchema;
+ }
+
+ public void accept(IInvokableInstance instance)
+ {
+ instance.appliesOnInstance((String partitionerString, String tokenString) -> {
+ IPartitioner partitioner = FBUtilities.newPartitioner(partitionerString);
+ List<Token> tokens = Collections.singletonList(partitioner.getTokenFactory().fromString(tokenString));
+ try
+ {
+ assert StorageService.instance.prepareForBootstrap(waitForSchema.toMillis()).size() == 0;
Review comment:
error message would be good
##########
File path: test/distributed/org/apache/cassandra/distributed/action/GossipHelper.java
##########
@@ -0,0 +1,455 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.distributed.action;
+
+import java.io.IOException;
+import java.io.Serializable;
+import java.net.InetSocketAddress;
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.TimeUnit;
+import java.util.function.Supplier;
+
+import org.apache.cassandra.db.SystemKeyspace;
+import org.apache.cassandra.dht.IPartitioner;
+import org.apache.cassandra.dht.Token;
+import org.apache.cassandra.distributed.api.IInstance;
+import org.apache.cassandra.distributed.api.IInvokableInstance;
+import org.apache.cassandra.distributed.api.IIsolatedExecutor;
+import org.apache.cassandra.distributed.shared.VersionedApplicationState;
+import org.apache.cassandra.gms.ApplicationState;
+import org.apache.cassandra.gms.EndpointState;
+import org.apache.cassandra.gms.Gossiper;
+import org.apache.cassandra.gms.VersionedValue;
+import org.apache.cassandra.io.util.DataInputBuffer;
+import org.apache.cassandra.io.util.DataOutputBuffer;
+import org.apache.cassandra.locator.InetAddressAndPort;
+import org.apache.cassandra.net.MessagingService;
+import org.apache.cassandra.schema.MigrationManager;
+import org.apache.cassandra.service.PendingRangeCalculatorService;
+import org.apache.cassandra.service.StorageService;
+import org.apache.cassandra.utils.FBUtilities;
+
+import static org.apache.cassandra.distributed.impl.DistributedTestSnitch.toCassandraInetAddressAndPort;
+
+public class GossipHelper
+{
+ public static InstanceAction statusToBootstrap(IInvokableInstance newNode)
+ {
+ return (instance) ->
+ {
+ changeGossipState(instance,
+ newNode,
+ Arrays.asList(tokens(newNode),
+ statusBootstrapping(newNode),
+ statusWithPortBootstrapping(newNode)));
+ };
+ }
+
+ public static InstanceAction statusToNormal(IInvokableInstance peer)
+ {
+ return (target) ->
+ {
+ changeGossipState(target,
+ peer,
+ Arrays.asList(tokens(peer),
+ statusNormal(peer),
+ releaseVersion(peer),
+ netVersion(peer),
+ statusWithPortNormal(peer)));
+ };
+ }
+
+ /**
+ * This method is unsafe and should be used _only_ when gossip is not used or available: it creates versioned values on the
+ * target instance, which means Gossip versioning gets out of sync. Use a safe couterpart at all times when performing _any_
+ * ring movement operations _or_ if Gossip is used.
+ */
+ public static void unsafeStatusToNormal(IInvokableInstance target, IInstance peer)
+ {
+ int messagingVersion = peer.getMessagingVersion();
+ changeGossipState(target,
+ peer,
+ Arrays.asList(unsafeVersionedValue(target,
+ ApplicationState.TOKENS,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).tokens(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeVersionedValue(target,
+ ApplicationState.STATUS,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeVersionedValue(target,
+ ApplicationState.STATUS_WITH_PORT,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeVersionedValue(target,
+ ApplicationState.NET_VERSION,
+ (partitioner) -> new VersionedValue.VersionedValueFactory(partitioner).networkVersion(messagingVersion),
+ peer.config().getString("partitioner")),
+ unsafeReleaseVersion(target,
+ peer.config().getString("partitioner"),
+ peer.getReleaseVersionString())));
+ }
+
+ public static InstanceAction statusToLeaving(IInvokableInstance newNode)
+ {
+ return (instance) -> {
+ changeGossipState(instance,
+ newNode,
+ Arrays.asList(tokens(newNode),
+ statusLeaving(newNode),
+ statusWithPortLeaving(newNode)));
+ };
+ }
+
+ public static InstanceAction bootstrap()
+ {
+ return new BootstrapAction();
+ }
+
+ public static InstanceAction bootstrap(boolean joinRing, Duration waitForBootstrap, Duration waitForSchema)
+ {
+ return new BootstrapAction(joinRing, waitForBootstrap, waitForSchema);
+ }
+
+ public static InstanceAction disseminateGossipState(IInvokableInstance newNode)
+ {
+ return new DisseminateGossipState(newNode);
+ }
+
+ public static InstanceAction pullSchemaFrom(IInvokableInstance pullFrom)
+ {
+ return new PullSchemaFrom(pullFrom);
+ }
+
+ private static InstanceAction disableBinary()
+ {
+ return (instance) -> instance.nodetoolResult("disablebinary").asserts().success();
+ }
+
+ private static class DisseminateGossipState implements InstanceAction
+ {
+ final Map<InetSocketAddress, byte[]> gossipState;
+
+ public DisseminateGossipState(IInvokableInstance... from)
+ {
+ gossipState = new HashMap<>();
+ for (IInvokableInstance node : from)
+ {
+ byte[] epBytes = node.callsOnInstance(() -> {
+ EndpointState epState = Gossiper.instance.getEndpointStateForEndpoint(FBUtilities.getBroadcastAddressAndPort());
+ return toBytes(epState);
+ }).call();
+ gossipState.put(node.broadcastAddress(), epBytes);
+ }
+ }
+
+ public void accept(IInvokableInstance instance)
+ {
+ instance.appliesOnInstance((IIsolatedExecutor.SerializableFunction<Map<InetSocketAddress, byte[]>, Void>)
+ (map) -> {
+ Map<InetAddressAndPort, EndpointState> newState = new HashMap<>();
+ for (Map.Entry<InetSocketAddress, byte[]> e : map.entrySet())
+ newState.put(toCassandraInetAddressAndPort(e.getKey()), fromBytes(e.getValue()));
+
+ Gossiper.runInGossipStageBlocking(() -> {
+ Gossiper.instance.applyStateLocally(newState);
+ });
+ return null;
+ }).apply(gossipState);
+ }
+ }
+
+ private static byte[] toBytes(EndpointState epState)
+ {
+ try (DataOutputBuffer out = new DataOutputBuffer(1024))
+ {
+ EndpointState.serializer.serialize(epState, out, MessagingService.current_version);
+ return out.toByteArray();
+ }
+ catch (IOException e)
+ {
+ throw new RuntimeException(e);
+ }
+ }
+
+ private static EndpointState fromBytes(byte[] bytes)
+ {
+ try (DataInputBuffer in = new DataInputBuffer(bytes))
+ {
+ return EndpointState.serializer.deserialize(in, MessagingService.current_version);
+ }
+ catch (Throwable t)
+ {
+ throw new RuntimeException(t);
+ }
+ }
+
+ private static class PullSchemaFrom implements InstanceAction
+ {
+ final InetSocketAddress pullFrom;
+
+ public PullSchemaFrom(IInvokableInstance pullFrom)
+ {
+ this.pullFrom = pullFrom.broadcastAddress();;
+ }
+
+ public void accept(IInvokableInstance pullTo)
+ {
+ pullTo.acceptsOnInstance((InetSocketAddress pullFrom) -> {
+ InetAddressAndPort endpoint = toCassandraInetAddressAndPort(pullFrom);
+ EndpointState state = Gossiper.instance.getEndpointStateForEndpoint(endpoint);
+ MigrationManager.scheduleSchemaPull(endpoint, state);
+ MigrationManager.waitUntilReadyForBootstrap();
+ }).accept(pullFrom);
+ }
+ }
+
+ private static class BootstrapAction implements InstanceAction, Serializable
+ {
+ private final boolean joinRing;
+ private final Duration waitForBootstrap;
+ private final Duration waitForSchema;
+
+ public BootstrapAction()
+ {
+ this(true, Duration.ofMinutes(10), Duration.ofSeconds(10));
+ }
+
+ public BootstrapAction(boolean joinRing, Duration waitForBootstrap, Duration waitForSchema)
+ {
+ this.joinRing = joinRing;
+ this.waitForBootstrap = waitForBootstrap;
+ this.waitForSchema = waitForSchema;
+ }
+
+ public void accept(IInvokableInstance instance)
+ {
+ instance.appliesOnInstance((String partitionerString, String tokenString) -> {
+ IPartitioner partitioner = FBUtilities.newPartitioner(partitionerString);
+ List<Token> tokens = Collections.singletonList(partitioner.getTokenFactory().fromString(tokenString));
+ try
+ {
+ assert StorageService.instance.prepareForBootstrap(waitForSchema.toMillis()).size() == 0;
+ assert StorageService.instance.bootstrap(tokens, waitForBootstrap.toMillis());
+ StorageService.instance.setUpDistributedSystemKeyspaces();
+ if (joinRing)
+ StorageService.instance.finishJoiningRing(true, tokens);
Review comment:
for me:
The following isn't needed as line 258 blocks replace
```
// remove the existing info about the replaced node.
if (!current.isEmpty())
{
Gossiper.runInGossipStageBlocking(() -> {
for (InetAddressAndPort existing : current)
Gossiper.instance.replacedEndpoint(existing);
});
}
```
If we allow replace later, we would need that logic as well.
##########
File path: test/distributed/org/apache/cassandra/distributed/action/GossipHelper.java
##########
@@ -0,0 +1,455 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.distributed.action;
+
+import java.io.IOException;
+import java.io.Serializable;
+import java.net.InetSocketAddress;
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.TimeUnit;
+import java.util.function.Supplier;
+
+import org.apache.cassandra.db.SystemKeyspace;
+import org.apache.cassandra.dht.IPartitioner;
+import org.apache.cassandra.dht.Token;
+import org.apache.cassandra.distributed.api.IInstance;
+import org.apache.cassandra.distributed.api.IInvokableInstance;
+import org.apache.cassandra.distributed.api.IIsolatedExecutor;
+import org.apache.cassandra.distributed.shared.VersionedApplicationState;
+import org.apache.cassandra.gms.ApplicationState;
+import org.apache.cassandra.gms.EndpointState;
+import org.apache.cassandra.gms.Gossiper;
+import org.apache.cassandra.gms.VersionedValue;
+import org.apache.cassandra.io.util.DataInputBuffer;
+import org.apache.cassandra.io.util.DataOutputBuffer;
+import org.apache.cassandra.locator.InetAddressAndPort;
+import org.apache.cassandra.net.MessagingService;
+import org.apache.cassandra.schema.MigrationManager;
+import org.apache.cassandra.service.PendingRangeCalculatorService;
+import org.apache.cassandra.service.StorageService;
+import org.apache.cassandra.utils.FBUtilities;
+
+import static org.apache.cassandra.distributed.impl.DistributedTestSnitch.toCassandraInetAddressAndPort;
+
+public class GossipHelper
+{
+ public static InstanceAction statusToBootstrap(IInvokableInstance newNode)
+ {
+ return (instance) ->
+ {
+ changeGossipState(instance,
+ newNode,
+ Arrays.asList(tokens(newNode),
+ statusBootstrapping(newNode),
+ statusWithPortBootstrapping(newNode)));
+ };
+ }
+
+ public static InstanceAction statusToNormal(IInvokableInstance peer)
+ {
+ return (target) ->
+ {
+ changeGossipState(target,
+ peer,
+ Arrays.asList(tokens(peer),
+ statusNormal(peer),
+ releaseVersion(peer),
+ netVersion(peer),
+ statusWithPortNormal(peer)));
+ };
+ }
+
+ /**
+ * This method is unsafe and should be used _only_ when gossip is not used or available: it creates versioned values on the
+ * target instance, which means Gossip versioning gets out of sync. Use a safe couterpart at all times when performing _any_
+ * ring movement operations _or_ if Gossip is used.
+ */
+ public static void unsafeStatusToNormal(IInvokableInstance target, IInstance peer)
+ {
+ int messagingVersion = peer.getMessagingVersion();
+ changeGossipState(target,
+ peer,
+ Arrays.asList(unsafeVersionedValue(target,
+ ApplicationState.TOKENS,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).tokens(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeVersionedValue(target,
+ ApplicationState.STATUS,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeVersionedValue(target,
+ ApplicationState.STATUS_WITH_PORT,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeVersionedValue(target,
+ ApplicationState.NET_VERSION,
+ (partitioner) -> new VersionedValue.VersionedValueFactory(partitioner).networkVersion(messagingVersion),
+ peer.config().getString("partitioner")),
+ unsafeReleaseVersion(target,
+ peer.config().getString("partitioner"),
+ peer.getReleaseVersionString())));
+ }
+
+ public static InstanceAction statusToLeaving(IInvokableInstance newNode)
+ {
+ return (instance) -> {
+ changeGossipState(instance,
+ newNode,
+ Arrays.asList(tokens(newNode),
+ statusLeaving(newNode),
+ statusWithPortLeaving(newNode)));
+ };
+ }
+
+ public static InstanceAction bootstrap()
+ {
+ return new BootstrapAction();
+ }
+
+ public static InstanceAction bootstrap(boolean joinRing, Duration waitForBootstrap, Duration waitForSchema)
+ {
+ return new BootstrapAction(joinRing, waitForBootstrap, waitForSchema);
+ }
+
+ public static InstanceAction disseminateGossipState(IInvokableInstance newNode)
+ {
+ return new DisseminateGossipState(newNode);
+ }
+
+ public static InstanceAction pullSchemaFrom(IInvokableInstance pullFrom)
+ {
+ return new PullSchemaFrom(pullFrom);
+ }
+
+ private static InstanceAction disableBinary()
+ {
+ return (instance) -> instance.nodetoolResult("disablebinary").asserts().success();
+ }
+
+ private static class DisseminateGossipState implements InstanceAction
+ {
+ final Map<InetSocketAddress, byte[]> gossipState;
+
+ public DisseminateGossipState(IInvokableInstance... from)
+ {
+ gossipState = new HashMap<>();
+ for (IInvokableInstance node : from)
+ {
+ byte[] epBytes = node.callsOnInstance(() -> {
+ EndpointState epState = Gossiper.instance.getEndpointStateForEndpoint(FBUtilities.getBroadcastAddressAndPort());
+ return toBytes(epState);
+ }).call();
+ gossipState.put(node.broadcastAddress(), epBytes);
+ }
+ }
+
+ public void accept(IInvokableInstance instance)
+ {
+ instance.appliesOnInstance((IIsolatedExecutor.SerializableFunction<Map<InetSocketAddress, byte[]>, Void>)
+ (map) -> {
+ Map<InetAddressAndPort, EndpointState> newState = new HashMap<>();
+ for (Map.Entry<InetSocketAddress, byte[]> e : map.entrySet())
+ newState.put(toCassandraInetAddressAndPort(e.getKey()), fromBytes(e.getValue()));
+
+ Gossiper.runInGossipStageBlocking(() -> {
+ Gossiper.instance.applyStateLocally(newState);
+ });
+ return null;
+ }).apply(gossipState);
+ }
+ }
+
+ private static byte[] toBytes(EndpointState epState)
+ {
+ try (DataOutputBuffer out = new DataOutputBuffer(1024))
+ {
+ EndpointState.serializer.serialize(epState, out, MessagingService.current_version);
+ return out.toByteArray();
+ }
+ catch (IOException e)
+ {
+ throw new RuntimeException(e);
+ }
+ }
+
+ private static EndpointState fromBytes(byte[] bytes)
+ {
+ try (DataInputBuffer in = new DataInputBuffer(bytes))
+ {
+ return EndpointState.serializer.deserialize(in, MessagingService.current_version);
+ }
+ catch (Throwable t)
+ {
+ throw new RuntimeException(t);
+ }
+ }
+
+ private static class PullSchemaFrom implements InstanceAction
+ {
+ final InetSocketAddress pullFrom;
+
+ public PullSchemaFrom(IInvokableInstance pullFrom)
+ {
+ this.pullFrom = pullFrom.broadcastAddress();;
+ }
+
+ public void accept(IInvokableInstance pullTo)
+ {
+ pullTo.acceptsOnInstance((InetSocketAddress pullFrom) -> {
+ InetAddressAndPort endpoint = toCassandraInetAddressAndPort(pullFrom);
+ EndpointState state = Gossiper.instance.getEndpointStateForEndpoint(endpoint);
+ MigrationManager.scheduleSchemaPull(endpoint, state);
+ MigrationManager.waitUntilReadyForBootstrap();
+ }).accept(pullFrom);
+ }
+ }
+
+ private static class BootstrapAction implements InstanceAction, Serializable
+ {
+ private final boolean joinRing;
+ private final Duration waitForBootstrap;
+ private final Duration waitForSchema;
+
+ public BootstrapAction()
+ {
+ this(true, Duration.ofMinutes(10), Duration.ofSeconds(10));
+ }
+
+ public BootstrapAction(boolean joinRing, Duration waitForBootstrap, Duration waitForSchema)
+ {
+ this.joinRing = joinRing;
+ this.waitForBootstrap = waitForBootstrap;
+ this.waitForSchema = waitForSchema;
+ }
+
+ public void accept(IInvokableInstance instance)
+ {
+ instance.appliesOnInstance((String partitionerString, String tokenString) -> {
+ IPartitioner partitioner = FBUtilities.newPartitioner(partitionerString);
+ List<Token> tokens = Collections.singletonList(partitioner.getTokenFactory().fromString(tokenString));
+ try
+ {
+ assert StorageService.instance.prepareForBootstrap(waitForSchema.toMillis()).size() == 0;
+ assert StorageService.instance.bootstrap(tokens, waitForBootstrap.toMillis());
Review comment:
error message would be good
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
[GitHub] [cassandra] ifesdjeen commented on a change in pull request #759: Improve machinery for testing bootstrap and range movements
Posted by GitBox <gi...@apache.org>.
ifesdjeen commented on a change in pull request #759:
URL: https://github.com/apache/cassandra/pull/759#discussion_r506118212
##########
File path: test/distributed/org/apache/cassandra/distributed/test/BootstrapTest.java
##########
@@ -18,85 +18,241 @@
package org.apache.cassandra.distributed.test;
+import java.net.InetSocketAddress;
+import java.time.Duration;
+import java.util.HashMap;
+import java.util.HashSet;
import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.locks.LockSupport;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.junit.Assert;
import org.junit.Test;
+import com.datastax.driver.core.ResultSet;
+import com.datastax.driver.core.Session;
+import com.datastax.driver.core.SimpleStatement;
+import com.datastax.driver.core.Statement;
+import com.datastax.driver.core.policies.RoundRobinPolicy;
+import org.apache.cassandra.dht.Range;
+import org.apache.cassandra.dht.Token;
import org.apache.cassandra.distributed.Cluster;
import org.apache.cassandra.distributed.api.ConsistencyLevel;
import org.apache.cassandra.distributed.api.ICluster;
import org.apache.cassandra.distributed.api.IInstanceConfig;
+import org.apache.cassandra.distributed.api.IInvokableInstance;
import org.apache.cassandra.distributed.api.TokenSupplier;
+import org.apache.cassandra.distributed.impl.DistributedTestSnitch;
+import org.apache.cassandra.distributed.impl.RowUtil;
import org.apache.cassandra.distributed.shared.NetworkTopology;
+import org.apache.cassandra.locator.EndpointsForRange;
+import org.apache.cassandra.locator.InetAddressAndPort;
+import org.apache.cassandra.service.StorageService;
+import static org.apache.cassandra.distributed.action.GossipHelper.bootstrap;
+import static org.apache.cassandra.distributed.action.GossipHelper.decomission;
+import static org.apache.cassandra.distributed.action.GossipHelper.disseminateGossipState;
+import static org.apache.cassandra.distributed.action.GossipHelper.pullSchemaFrom;
+import static org.apache.cassandra.distributed.action.GossipHelper.statusToBootstrap;
import static org.apache.cassandra.distributed.api.Feature.GOSSIP;
+import static org.apache.cassandra.distributed.api.Feature.NATIVE_PROTOCOL;
import static org.apache.cassandra.distributed.api.Feature.NETWORK;
+import static org.apache.cassandra.distributed.shared.AssertUtils.assertRows;
+import static org.apache.cassandra.distributed.shared.AssertUtils.row;
-// TODO: this test should be removed after running in-jvm dtests is set up via the shared API repository
public class BootstrapTest extends TestBaseImpl
{
-
@Test
public void bootstrapTest() throws Throwable
{
int originalNodeCount = 2;
int expandedNodeCount = originalNodeCount + 1;
- Cluster.Builder builder = builder().withNodes(originalNodeCount)
- .withTokenSupplier(TokenSupplier.evenlyDistributedTokens(expandedNodeCount))
- .withNodeIdTopology(NetworkTopology.singleDcNetworkTopology(expandedNodeCount, "dc0", "rack0"))
- .withConfig(config -> config.with(NETWORK, GOSSIP));
-
- Map<Integer, Long> withBootstrap = null;
- Map<Integer, Long> naturally = null;
- try (Cluster cluster = builder.withNodes(originalNodeCount).start())
+
+ try (Cluster cluster = builder().withNodes(originalNodeCount)
+ .withTokenSupplier(TokenSupplier.evenlyDistributedTokens(expandedNodeCount))
+ .withNodeIdTopology(NetworkTopology.singleDcNetworkTopology(expandedNodeCount, "dc0", "rack0"))
+ .withConfig(config -> config.with(NETWORK, GOSSIP))
+ .start())
{
- populate(cluster);
+ populate(cluster,0, 100);
IInstanceConfig config = cluster.newInstanceConfig();
- config.set("auto_bootstrap", true);
-
- cluster.bootstrap(config).startup();
+ IInvokableInstance newInstance = cluster.initialize(config);
+ withJoinRing(false, () -> newInstance.startup(cluster));
- cluster.stream().forEach(instance -> {
- instance.nodetool("cleanup", KEYSPACE, "tbl");
- });
+ cluster.run(statusToBootstrap(newInstance));
Review comment:
Resolvinig since this got addressed below.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
[GitHub] [cassandra] dcapwell commented on a change in pull request #759: Improve machinery for testing bootstrap and range movements
Posted by GitBox <gi...@apache.org>.
dcapwell commented on a change in pull request #759:
URL: https://github.com/apache/cassandra/pull/759#discussion_r504130027
##########
File path: test/distributed/org/apache/cassandra/distributed/action/GossipHelper.java
##########
@@ -0,0 +1,464 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.distributed.action;
+
+
+import java.io.IOException;
+import java.net.InetSocketAddress;
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.TimeUnit;
+import java.util.function.Predicate;
+import java.util.stream.Stream;
+
+import net.openhft.chronicle.core.util.SerializableBiFunction;
+import net.openhft.chronicle.core.util.SerializableConsumer;
+import org.apache.cassandra.db.SystemKeyspace;
+import org.apache.cassandra.dht.IPartitioner;
+import org.apache.cassandra.dht.Token;
+import org.apache.cassandra.distributed.api.ICluster;
+import org.apache.cassandra.distributed.api.IInstance;
+import org.apache.cassandra.distributed.api.IInvokableInstance;
+import org.apache.cassandra.distributed.api.IIsolatedExecutor;
+import org.apache.cassandra.distributed.impl.Instance;
+import org.apache.cassandra.distributed.shared.VersionedApplicationState;
+import org.apache.cassandra.gms.ApplicationState;
+import org.apache.cassandra.gms.EndpointState;
+import org.apache.cassandra.gms.Gossiper;
+import org.apache.cassandra.gms.VersionedValue;
+import org.apache.cassandra.io.util.DataInputBuffer;
+import org.apache.cassandra.io.util.DataOutputBuffer;
+import org.apache.cassandra.locator.InetAddressAndPort;
+import org.apache.cassandra.locator.TokenMetadata;
+import org.apache.cassandra.net.MessagingService;
+import org.apache.cassandra.schema.MigrationManager;
+import org.apache.cassandra.service.PendingRangeCalculatorService;
+import org.apache.cassandra.service.StorageService;
+import org.apache.cassandra.utils.FBUtilities;
+
+import static org.apache.cassandra.distributed.impl.DistributedTestSnitch.toCassandraInetAddressAndPort;
+
+
+public class GossipHelper
+{
+
+ public static ClusterAction clusterAction(InstanceAction action)
Review comment:
in your examples there are no real differences between `run` and `forEach`, so I rather have `forEach` only. An issue we face today is that Instance has a lot of similar, but slightly different methods, which means people mess these up all the time; having two functions that do the same thing worries me about adding extra complexity.
API signatures
```
public abstract class AbstractCluster<I extends IInstance> implements ICluster<I>, AutoCloseable
{
...
public void forEach(Consumer<? super I> consumer)
...
public void run(InstanceAction action)
..
public interface InstanceAction extends Serializable
{
void apply(IInvokableInstance target);
}
```
So the main difference is that we hard code the interface rather than relying on what the cluster provides, and Serializable (but this isn't safe as it works with Instance, which isn't Serializable).
Also, the current InstancAction has cluster as the first argument, we can always update forEach to offer a BiConsumer
```
public void forEach(BiConsumer<? super ICluster<I>, ? super I> consumer) // note, we can change the signature of AbstractCluster to capture the concrete type, this would make it so you can code against Cluster or UpgradeCluster rather than the interface
```
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
[GitHub] [cassandra] ifesdjeen commented on a change in pull request #759: Improve machinery for testing bootstrap and range movements
Posted by GitBox <gi...@apache.org>.
ifesdjeen commented on a change in pull request #759:
URL: https://github.com/apache/cassandra/pull/759#discussion_r504034381
##########
File path: test/distributed/org/apache/cassandra/distributed/impl/IsolatedExecutor.java
##########
@@ -139,6 +139,10 @@
private static <E extends Serializable> E transferOneObject(E object, ClassLoader classLoader, Method deserializeOnInstance)
{
+ // already the right object
+ if (object.getClass().getClassLoader() == classLoader)
Review comment:
Removed this. I think there was some issue that has lead me here but i forgot what that was...
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
[GitHub] [cassandra] dcapwell commented on a change in pull request #759: Improve machinery for testing bootstrap and range movements
Posted by GitBox <gi...@apache.org>.
dcapwell commented on a change in pull request #759:
URL: https://github.com/apache/cassandra/pull/759#discussion_r504253562
##########
File path: src/java/org/apache/cassandra/gms/VersionedValue.java
##########
@@ -27,6 +27,7 @@
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.Iterables;
+import com.fasterxml.jackson.core.Versioned;
Review comment:
can you remove? not used.
##########
File path: src/java/org/apache/cassandra/gms/Gossiper.java
##########
@@ -825,7 +854,7 @@ private void maybeGossipToUnreachableMember(Message<GossipDigestSyn> message)
double prob = unreachableEndpointCount / (liveEndpointCount + 1);
double randDbl = random.nextDouble();
if (randDbl < prob)
- sendGossip(message, unreachableEndpoints.keySet());
+ sendGossip(message, unreachableEndpoints.keySet(), ep -> !isDeadState(getEndpointStateMap().get(ep)));
Review comment:
think you can use `endpointStateMap` directly to avoid copying the map.
Also wondering if it is possible that it returns null, so may need to do a null check to avoid NPE. As far as I can tell, `org.apache.cassandra.gms.Gossiper#maybeGossipToUnreachableMember` is only called on the gossiper thread, so removal from the map should also be in the same thread (outside of tests), so not sure if it should ever happen...
##########
File path: test/distributed/org/apache/cassandra/distributed/test/BootstrapTest.java
##########
@@ -18,85 +18,241 @@
package org.apache.cassandra.distributed.test;
+import java.net.InetSocketAddress;
+import java.time.Duration;
+import java.util.HashMap;
+import java.util.HashSet;
import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.locks.LockSupport;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.junit.Assert;
import org.junit.Test;
+import com.datastax.driver.core.ResultSet;
+import com.datastax.driver.core.Session;
+import com.datastax.driver.core.SimpleStatement;
+import com.datastax.driver.core.Statement;
+import com.datastax.driver.core.policies.RoundRobinPolicy;
+import org.apache.cassandra.dht.Range;
+import org.apache.cassandra.dht.Token;
import org.apache.cassandra.distributed.Cluster;
import org.apache.cassandra.distributed.api.ConsistencyLevel;
import org.apache.cassandra.distributed.api.ICluster;
import org.apache.cassandra.distributed.api.IInstanceConfig;
+import org.apache.cassandra.distributed.api.IInvokableInstance;
import org.apache.cassandra.distributed.api.TokenSupplier;
+import org.apache.cassandra.distributed.impl.DistributedTestSnitch;
+import org.apache.cassandra.distributed.impl.RowUtil;
import org.apache.cassandra.distributed.shared.NetworkTopology;
+import org.apache.cassandra.locator.EndpointsForRange;
+import org.apache.cassandra.locator.InetAddressAndPort;
+import org.apache.cassandra.service.StorageService;
+import static org.apache.cassandra.distributed.action.GossipHelper.bootstrap;
+import static org.apache.cassandra.distributed.action.GossipHelper.decomission;
+import static org.apache.cassandra.distributed.action.GossipHelper.disseminateGossipState;
+import static org.apache.cassandra.distributed.action.GossipHelper.pullSchemaFrom;
+import static org.apache.cassandra.distributed.action.GossipHelper.statusToBootstrap;
import static org.apache.cassandra.distributed.api.Feature.GOSSIP;
+import static org.apache.cassandra.distributed.api.Feature.NATIVE_PROTOCOL;
import static org.apache.cassandra.distributed.api.Feature.NETWORK;
+import static org.apache.cassandra.distributed.shared.AssertUtils.assertRows;
+import static org.apache.cassandra.distributed.shared.AssertUtils.row;
-// TODO: this test should be removed after running in-jvm dtests is set up via the shared API repository
public class BootstrapTest extends TestBaseImpl
{
-
@Test
public void bootstrapTest() throws Throwable
{
int originalNodeCount = 2;
int expandedNodeCount = originalNodeCount + 1;
- Cluster.Builder builder = builder().withNodes(originalNodeCount)
- .withTokenSupplier(TokenSupplier.evenlyDistributedTokens(expandedNodeCount))
- .withNodeIdTopology(NetworkTopology.singleDcNetworkTopology(expandedNodeCount, "dc0", "rack0"))
- .withConfig(config -> config.with(NETWORK, GOSSIP));
-
- Map<Integer, Long> withBootstrap = null;
- Map<Integer, Long> naturally = null;
- try (Cluster cluster = builder.withNodes(originalNodeCount).start())
+
+ try (Cluster cluster = builder().withNodes(originalNodeCount)
+ .withTokenSupplier(TokenSupplier.evenlyDistributedTokens(expandedNodeCount))
+ .withNodeIdTopology(NetworkTopology.singleDcNetworkTopology(expandedNodeCount, "dc0", "rack0"))
+ .withConfig(config -> config.with(NETWORK, GOSSIP))
+ .start())
{
- populate(cluster);
+ populate(cluster,0, 100);
IInstanceConfig config = cluster.newInstanceConfig();
- config.set("auto_bootstrap", true);
-
- cluster.bootstrap(config).startup();
+ IInvokableInstance newInstance = cluster.initialize(config);
+ withJoinRing(false, () -> newInstance.startup(cluster));
- cluster.stream().forEach(instance -> {
- instance.nodetool("cleanup", KEYSPACE, "tbl");
- });
+ cluster.run(statusToBootstrap(newInstance));
Review comment:
If you turn off joining the ring and disable autoboostrap (dtest default) then when you call `nodetool join` it will join the ring without bootstrapping (since autoboostrap=false). This test runs in that state, but then tries to bootstrap (which I don't think is currently possible), so feels like its testing a state we don't allow an operator to put us in?
If we add back auto_bootstrap=true then this logic can be replaced by
```
IInstanceConfig config = cluster.newInstanceConfig();
config.set("auto_bootstrap", true);
IInvokableInstance newInstance = cluster.initialize(config);
withJoinRing(false, () -> newInstance.startup(cluster));
newInstance.nodetoolResult("join").asserts().success();
```
##########
File path: test/distributed/org/apache/cassandra/distributed/test/BootstrapTest.java
##########
@@ -18,85 +18,241 @@
package org.apache.cassandra.distributed.test;
+import java.net.InetSocketAddress;
+import java.time.Duration;
+import java.util.HashMap;
+import java.util.HashSet;
import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.locks.LockSupport;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.junit.Assert;
import org.junit.Test;
+import com.datastax.driver.core.ResultSet;
+import com.datastax.driver.core.Session;
+import com.datastax.driver.core.SimpleStatement;
+import com.datastax.driver.core.Statement;
+import com.datastax.driver.core.policies.RoundRobinPolicy;
+import org.apache.cassandra.dht.Range;
+import org.apache.cassandra.dht.Token;
import org.apache.cassandra.distributed.Cluster;
import org.apache.cassandra.distributed.api.ConsistencyLevel;
import org.apache.cassandra.distributed.api.ICluster;
import org.apache.cassandra.distributed.api.IInstanceConfig;
+import org.apache.cassandra.distributed.api.IInvokableInstance;
import org.apache.cassandra.distributed.api.TokenSupplier;
+import org.apache.cassandra.distributed.impl.DistributedTestSnitch;
+import org.apache.cassandra.distributed.impl.RowUtil;
import org.apache.cassandra.distributed.shared.NetworkTopology;
+import org.apache.cassandra.locator.EndpointsForRange;
+import org.apache.cassandra.locator.InetAddressAndPort;
+import org.apache.cassandra.service.StorageService;
+import static org.apache.cassandra.distributed.action.GossipHelper.bootstrap;
+import static org.apache.cassandra.distributed.action.GossipHelper.decomission;
+import static org.apache.cassandra.distributed.action.GossipHelper.disseminateGossipState;
+import static org.apache.cassandra.distributed.action.GossipHelper.pullSchemaFrom;
+import static org.apache.cassandra.distributed.action.GossipHelper.statusToBootstrap;
import static org.apache.cassandra.distributed.api.Feature.GOSSIP;
+import static org.apache.cassandra.distributed.api.Feature.NATIVE_PROTOCOL;
import static org.apache.cassandra.distributed.api.Feature.NETWORK;
+import static org.apache.cassandra.distributed.shared.AssertUtils.assertRows;
+import static org.apache.cassandra.distributed.shared.AssertUtils.row;
-// TODO: this test should be removed after running in-jvm dtests is set up via the shared API repository
public class BootstrapTest extends TestBaseImpl
{
-
@Test
public void bootstrapTest() throws Throwable
{
int originalNodeCount = 2;
int expandedNodeCount = originalNodeCount + 1;
- Cluster.Builder builder = builder().withNodes(originalNodeCount)
- .withTokenSupplier(TokenSupplier.evenlyDistributedTokens(expandedNodeCount))
- .withNodeIdTopology(NetworkTopology.singleDcNetworkTopology(expandedNodeCount, "dc0", "rack0"))
- .withConfig(config -> config.with(NETWORK, GOSSIP));
-
- Map<Integer, Long> withBootstrap = null;
- Map<Integer, Long> naturally = null;
- try (Cluster cluster = builder.withNodes(originalNodeCount).start())
+
+ try (Cluster cluster = builder().withNodes(originalNodeCount)
+ .withTokenSupplier(TokenSupplier.evenlyDistributedTokens(expandedNodeCount))
+ .withNodeIdTopology(NetworkTopology.singleDcNetworkTopology(expandedNodeCount, "dc0", "rack0"))
+ .withConfig(config -> config.with(NETWORK, GOSSIP))
+ .start())
{
- populate(cluster);
+ populate(cluster,0, 100);
IInstanceConfig config = cluster.newInstanceConfig();
- config.set("auto_bootstrap", true);
-
- cluster.bootstrap(config).startup();
+ IInvokableInstance newInstance = cluster.initialize(config);
+ withJoinRing(false, () -> newInstance.startup(cluster));
- cluster.stream().forEach(instance -> {
- instance.nodetool("cleanup", KEYSPACE, "tbl");
- });
+ cluster.run(statusToBootstrap(newInstance));
+ cluster.run(pullSchemaFrom(cluster.get(1)), newInstance.config().num());
+ cluster.run(bootstrap(), newInstance.config().num());
- withBootstrap = count(cluster);
+ for (Map.Entry<Integer, Long> e : count(cluster).entrySet())
+ Assert.assertEquals(e.getValue().longValue(), 100L);
}
+ }
- builder = builder.withNodes(expandedNodeCount)
- .withTokenSupplier(TokenSupplier.evenlyDistributedTokens(expandedNodeCount))
- .withConfig(config -> config.with(NETWORK, GOSSIP));
+ @Test
+ public void testPendingWrites() throws Throwable
+ {
+ int originalNodeCount = 2;
+ int expandedNodeCount = originalNodeCount + 1;
- try (ICluster cluster = builder.start())
+ try (Cluster cluster = builder().withNodes(originalNodeCount)
+ .withTokenSupplier(TokenSupplier.evenlyDistributedTokens(expandedNodeCount))
+ .withNodeIdTopology(NetworkTopology.singleDcNetworkTopology(expandedNodeCount, "dc0", "rack0"))
+ .withConfig(config -> config.with(NETWORK, GOSSIP))
+ .start())
{
- populate(cluster);
- naturally = count(cluster);
+ populate(cluster, 0, 100);
+ IInstanceConfig config = cluster.newInstanceConfig();
+ IInvokableInstance newInstance = cluster.initialize(config);
+ withJoinRing(false, () -> newInstance.startup(cluster));
+
+ cluster.run(statusToBootstrap(newInstance));
+ cluster.run(bootstrap(false, Duration.ofSeconds(60), Duration.ofSeconds(60)), newInstance.config().num());
+
+ cluster.get(1).acceptsOnInstance((InetSocketAddress ip) -> {
+ Set<InetAddressAndPort> set = new HashSet<>();
+ for (Map.Entry<Range<Token>, EndpointsForRange.Builder> e : StorageService.instance.getTokenMetadata().getPendingRanges(KEYSPACE))
+ {
+ set.addAll(e.getValue().build().endpoints());
+ }
+ Assert.assertEquals(set.size(), 1);
+ Assert.assertTrue(String.format("%s should contain %s", set, ip),
+ set.contains(DistributedTestSnitch.toCassandraInetAddressAndPort(ip)));
+ }).accept(cluster.get(3).broadcastAddress());
+
+ populate(cluster, 100, 150);
+
+ newInstance.nodetoolResult("join").asserts().success();
+
+ cluster.run(disseminateGossipState(newInstance),1, 2);
+
+ cluster.get(1).acceptsOnInstance((InetSocketAddress ip) -> {
+ Set<InetAddressAndPort> set = new HashSet<>();
+ for (Map.Entry<Range<Token>, EndpointsForRange.Builder> e : StorageService.instance.getTokenMetadata().getPendingRanges(KEYSPACE))
+ set.addAll(e.getValue().build().endpoints());
+ assert set.size() == 0 : set;
+ }).accept(cluster.get(3).broadcastAddress());
+
+ for (Map.Entry<Integer, Long> e : count(cluster).entrySet())
+ Assert.assertEquals(e.getValue().longValue(), 150L);
}
+ }
+
+ @Test
+ public void internodeConnectionsDuringDecom() throws Throwable
+ {
+ try (Cluster cluster = builder().withNodes(4)
+ .withConfig(config -> config.with(NETWORK, GOSSIP, NATIVE_PROTOCOL))
+ .start())
+ {
+ populate(cluster, 0, 100);
+
+ cluster.run(decomission(), 1);
- for (Map.Entry<Integer, Long> e : withBootstrap.entrySet())
- Assert.assertTrue(e.getValue() >= naturally.get(e.getKey()));
+ cluster.filters().allVerbs().from(1).messagesMatching((i, i1, iMessage) -> {
+ throw new AssertionError("Decomissioned node should not send any messages");
+ }).drop();
+
+
+ Map<Integer, Long> connectionAttempts = new HashMap<>();
+ long deadline = System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(10);
+
+ // Wait 10 seconds and check if there are any new connection attempts to the decomissioned node
+ while (System.currentTimeMillis() <= deadline)
+ {
+ for (int i = 2; i <= cluster.size(); i++)
+ {
+ Object[][] res = cluster.get(i).executeInternal("SELECT active_connections, connection_attempts FROM system_views.internode_outbound WHERE address = '127.0.0.1' AND port = 7012");
Review comment:
Yay! views!
##########
File path: test/distributed/org/apache/cassandra/distributed/test/BootstrapTest.java
##########
@@ -18,85 +18,241 @@
package org.apache.cassandra.distributed.test;
+import java.net.InetSocketAddress;
+import java.time.Duration;
+import java.util.HashMap;
+import java.util.HashSet;
import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.locks.LockSupport;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.junit.Assert;
import org.junit.Test;
+import com.datastax.driver.core.ResultSet;
+import com.datastax.driver.core.Session;
+import com.datastax.driver.core.SimpleStatement;
+import com.datastax.driver.core.Statement;
+import com.datastax.driver.core.policies.RoundRobinPolicy;
+import org.apache.cassandra.dht.Range;
+import org.apache.cassandra.dht.Token;
import org.apache.cassandra.distributed.Cluster;
import org.apache.cassandra.distributed.api.ConsistencyLevel;
import org.apache.cassandra.distributed.api.ICluster;
import org.apache.cassandra.distributed.api.IInstanceConfig;
+import org.apache.cassandra.distributed.api.IInvokableInstance;
import org.apache.cassandra.distributed.api.TokenSupplier;
+import org.apache.cassandra.distributed.impl.DistributedTestSnitch;
+import org.apache.cassandra.distributed.impl.RowUtil;
import org.apache.cassandra.distributed.shared.NetworkTopology;
+import org.apache.cassandra.locator.EndpointsForRange;
+import org.apache.cassandra.locator.InetAddressAndPort;
+import org.apache.cassandra.service.StorageService;
+import static org.apache.cassandra.distributed.action.GossipHelper.bootstrap;
+import static org.apache.cassandra.distributed.action.GossipHelper.decomission;
+import static org.apache.cassandra.distributed.action.GossipHelper.disseminateGossipState;
+import static org.apache.cassandra.distributed.action.GossipHelper.pullSchemaFrom;
+import static org.apache.cassandra.distributed.action.GossipHelper.statusToBootstrap;
import static org.apache.cassandra.distributed.api.Feature.GOSSIP;
+import static org.apache.cassandra.distributed.api.Feature.NATIVE_PROTOCOL;
import static org.apache.cassandra.distributed.api.Feature.NETWORK;
+import static org.apache.cassandra.distributed.shared.AssertUtils.assertRows;
+import static org.apache.cassandra.distributed.shared.AssertUtils.row;
-// TODO: this test should be removed after running in-jvm dtests is set up via the shared API repository
public class BootstrapTest extends TestBaseImpl
{
-
@Test
public void bootstrapTest() throws Throwable
{
int originalNodeCount = 2;
int expandedNodeCount = originalNodeCount + 1;
- Cluster.Builder builder = builder().withNodes(originalNodeCount)
- .withTokenSupplier(TokenSupplier.evenlyDistributedTokens(expandedNodeCount))
- .withNodeIdTopology(NetworkTopology.singleDcNetworkTopology(expandedNodeCount, "dc0", "rack0"))
- .withConfig(config -> config.with(NETWORK, GOSSIP));
-
- Map<Integer, Long> withBootstrap = null;
- Map<Integer, Long> naturally = null;
- try (Cluster cluster = builder.withNodes(originalNodeCount).start())
+
+ try (Cluster cluster = builder().withNodes(originalNodeCount)
+ .withTokenSupplier(TokenSupplier.evenlyDistributedTokens(expandedNodeCount))
+ .withNodeIdTopology(NetworkTopology.singleDcNetworkTopology(expandedNodeCount, "dc0", "rack0"))
+ .withConfig(config -> config.with(NETWORK, GOSSIP))
+ .start())
{
- populate(cluster);
+ populate(cluster,0, 100);
IInstanceConfig config = cluster.newInstanceConfig();
- config.set("auto_bootstrap", true);
-
- cluster.bootstrap(config).startup();
+ IInvokableInstance newInstance = cluster.initialize(config);
+ withJoinRing(false, () -> newInstance.startup(cluster));
- cluster.stream().forEach(instance -> {
- instance.nodetool("cleanup", KEYSPACE, "tbl");
- });
+ cluster.run(statusToBootstrap(newInstance));
Review comment:
I took a stab and changed the test to do join in https://github.com/dcapwell/cassandra/commit/935f78b101484f6dfee473fd5375a31761f02b39
##########
File path: test/distributed/org/apache/cassandra/distributed/impl/Instance.java
##########
@@ -443,25 +457,31 @@ public void startup(ICluster cluster)
StorageService.instance.registerDaemon(CassandraDaemon.getInstanceForTesting());
if (config.has(GOSSIP))
{
+ MigrationManager.setUptimeFn(() -> System.currentTimeMillis() - startedAt);
Review comment:
Given that this is for tests this should be fine, but it might be better to do nanos then convert to mills (to avoid time going backwards)
##########
File path: src/java/org/apache/cassandra/gms/Gossiper.java
##########
@@ -777,23 +787,42 @@ public int getCurrentGenerationNumber(InetAddressAndPort endpoint)
return endpointStateMap.get(endpoint).getHeartBeatState().getGeneration();
}
+ private boolean sendGossip(Message<GossipDigestSyn> message, Set<InetAddressAndPort> epSet)
+ {
+ return sendGossip(message, epSet, null);
+ }
+
/**
* Returns true if the chosen target was also a seed. False otherwise
*
* @param message
* @param epSet a set of endpoint from which a random endpoint is chosen.
+ * @param filter whether or not we should attempt to gossip to this node in the first place
* @return true if the chosen endpoint is also a seed.
*/
- private boolean sendGossip(Message<GossipDigestSyn> message, Set<InetAddressAndPort> epSet)
+ private boolean sendGossip(Message<GossipDigestSyn> message, Set<InetAddressAndPort> epSet, Predicate<InetAddressAndPort> filter)
Review comment:
any reason to not just have the caller call `com.google.common.collect.Sets#filter(java.util.Set<E>, com.google.common.base.Predicate<? super E>)`? I am ok with this change, mostly curious.
##########
File path: src/java/org/apache/cassandra/service/LoadBroadcaster.java
##########
@@ -87,6 +87,8 @@ public void startBroadcasting()
{
public void run()
{
+ if (!Gossiper.instance.isEnabled())
Review comment:
this has a race condition bug, can you update isEnabled to be
```
public boolean isEnabled()
{
ScheduledFuture<?> scheduledGossipTask = this.scheduledGossipTask;
return (scheduledGossipTask != null) && (!scheduledGossipTask.isCancelled());
}
```
right now the null check may see a ref, but then the next step tries to reload the ref and gets a null, causing a NPE
##########
File path: test/distributed/org/apache/cassandra/distributed/test/BootstrapTest.java
##########
@@ -18,85 +18,241 @@
package org.apache.cassandra.distributed.test;
+import java.net.InetSocketAddress;
+import java.time.Duration;
+import java.util.HashMap;
+import java.util.HashSet;
import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.locks.LockSupport;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.junit.Assert;
import org.junit.Test;
+import com.datastax.driver.core.ResultSet;
+import com.datastax.driver.core.Session;
+import com.datastax.driver.core.SimpleStatement;
+import com.datastax.driver.core.Statement;
+import com.datastax.driver.core.policies.RoundRobinPolicy;
+import org.apache.cassandra.dht.Range;
+import org.apache.cassandra.dht.Token;
import org.apache.cassandra.distributed.Cluster;
import org.apache.cassandra.distributed.api.ConsistencyLevel;
import org.apache.cassandra.distributed.api.ICluster;
import org.apache.cassandra.distributed.api.IInstanceConfig;
+import org.apache.cassandra.distributed.api.IInvokableInstance;
import org.apache.cassandra.distributed.api.TokenSupplier;
+import org.apache.cassandra.distributed.impl.DistributedTestSnitch;
+import org.apache.cassandra.distributed.impl.RowUtil;
import org.apache.cassandra.distributed.shared.NetworkTopology;
+import org.apache.cassandra.locator.EndpointsForRange;
+import org.apache.cassandra.locator.InetAddressAndPort;
+import org.apache.cassandra.service.StorageService;
+import static org.apache.cassandra.distributed.action.GossipHelper.bootstrap;
+import static org.apache.cassandra.distributed.action.GossipHelper.decomission;
+import static org.apache.cassandra.distributed.action.GossipHelper.disseminateGossipState;
+import static org.apache.cassandra.distributed.action.GossipHelper.pullSchemaFrom;
+import static org.apache.cassandra.distributed.action.GossipHelper.statusToBootstrap;
import static org.apache.cassandra.distributed.api.Feature.GOSSIP;
+import static org.apache.cassandra.distributed.api.Feature.NATIVE_PROTOCOL;
import static org.apache.cassandra.distributed.api.Feature.NETWORK;
+import static org.apache.cassandra.distributed.shared.AssertUtils.assertRows;
+import static org.apache.cassandra.distributed.shared.AssertUtils.row;
-// TODO: this test should be removed after running in-jvm dtests is set up via the shared API repository
public class BootstrapTest extends TestBaseImpl
{
-
@Test
public void bootstrapTest() throws Throwable
{
int originalNodeCount = 2;
int expandedNodeCount = originalNodeCount + 1;
- Cluster.Builder builder = builder().withNodes(originalNodeCount)
- .withTokenSupplier(TokenSupplier.evenlyDistributedTokens(expandedNodeCount))
- .withNodeIdTopology(NetworkTopology.singleDcNetworkTopology(expandedNodeCount, "dc0", "rack0"))
- .withConfig(config -> config.with(NETWORK, GOSSIP));
-
- Map<Integer, Long> withBootstrap = null;
- Map<Integer, Long> naturally = null;
- try (Cluster cluster = builder.withNodes(originalNodeCount).start())
+
+ try (Cluster cluster = builder().withNodes(originalNodeCount)
+ .withTokenSupplier(TokenSupplier.evenlyDistributedTokens(expandedNodeCount))
+ .withNodeIdTopology(NetworkTopology.singleDcNetworkTopology(expandedNodeCount, "dc0", "rack0"))
+ .withConfig(config -> config.with(NETWORK, GOSSIP))
+ .start())
{
- populate(cluster);
+ populate(cluster,0, 100);
IInstanceConfig config = cluster.newInstanceConfig();
- config.set("auto_bootstrap", true);
-
- cluster.bootstrap(config).startup();
+ IInvokableInstance newInstance = cluster.initialize(config);
+ withJoinRing(false, () -> newInstance.startup(cluster));
- cluster.stream().forEach(instance -> {
- instance.nodetool("cleanup", KEYSPACE, "tbl");
- });
+ cluster.run(statusToBootstrap(newInstance));
+ cluster.run(pullSchemaFrom(cluster.get(1)), newInstance.config().num());
+ cluster.run(bootstrap(), newInstance.config().num());
- withBootstrap = count(cluster);
+ for (Map.Entry<Integer, Long> e : count(cluster).entrySet())
+ Assert.assertEquals(e.getValue().longValue(), 100L);
}
+ }
- builder = builder.withNodes(expandedNodeCount)
- .withTokenSupplier(TokenSupplier.evenlyDistributedTokens(expandedNodeCount))
- .withConfig(config -> config.with(NETWORK, GOSSIP));
+ @Test
+ public void testPendingWrites() throws Throwable
+ {
+ int originalNodeCount = 2;
+ int expandedNodeCount = originalNodeCount + 1;
- try (ICluster cluster = builder.start())
+ try (Cluster cluster = builder().withNodes(originalNodeCount)
+ .withTokenSupplier(TokenSupplier.evenlyDistributedTokens(expandedNodeCount))
+ .withNodeIdTopology(NetworkTopology.singleDcNetworkTopology(expandedNodeCount, "dc0", "rack0"))
+ .withConfig(config -> config.with(NETWORK, GOSSIP))
+ .start())
{
- populate(cluster);
- naturally = count(cluster);
+ populate(cluster, 0, 100);
+ IInstanceConfig config = cluster.newInstanceConfig();
+ IInvokableInstance newInstance = cluster.initialize(config);
+ withJoinRing(false, () -> newInstance.startup(cluster));
+
+ cluster.run(statusToBootstrap(newInstance));
+ cluster.run(bootstrap(false, Duration.ofSeconds(60), Duration.ofSeconds(60)), newInstance.config().num());
Review comment:
been running in a debugger and see that this doesn't properly update the bootstrap state, for this reason join thinks a bootstrap never happened and rebootstraps everything; was also seeing a few other subtle difference than `org.apache.cassandra.service.StorageService#joinTokenRing`.
Rather than try to do this, why not allow startup to bootstrap/join or rely on join to bootstrap (when cassandra.join_ring=false)? This would actually match the operator flow so the test would touch the normal code paths.
I took a stab at it in https://github.com/dcapwell/cassandra/commit/935f78b101484f6dfee473fd5375a31761f02b39 where I run join in the background, and block streaming (to make sure test wasn't flaky); this seems to mostly match the intent (while bootstrapping there are writes).
##########
File path: src/java/org/apache/cassandra/gms/Gossiper.java
##########
@@ -707,6 +707,17 @@ public void unsafeAssassinateEndpoint(String address) throws UnknownHostExceptio
assassinateEndpoint(address);
}
+
+ @VisibleForTesting
+ public void unsafeAnulEndpoint(InetAddressAndPort endpoint)
Review comment:
I know this is called `unsafe` but should we wrap in `Gossiper.runInGossipStageBlocking` to make sure we don't add race conditions on remove? The only user at the moment is gossip helper (shown below) and does the wrapping itself, so is currently safe I believe
```
Gossiper.runInGossipStageBlocking(() -> Gossiper.instance.unsafeAnulEndpoint(endpoint));
```
##########
File path: src/java/org/apache/cassandra/service/StorageService.java
##########
@@ -622,6 +624,11 @@ public synchronized void initServer() throws ConfigurationException
}
public synchronized void initServer(int delay) throws ConfigurationException
+ {
+ initServer(delay, joinRing);
+ }
+
+ public synchronized void initServer(int delay, boolean joinRing) throws ConfigurationException
Review comment:
you removed the logic that needed this, so we can remove
##########
File path: test/distributed/org/apache/cassandra/distributed/test/BootstrapTest.java
##########
@@ -18,85 +18,241 @@
package org.apache.cassandra.distributed.test;
+import java.net.InetSocketAddress;
+import java.time.Duration;
+import java.util.HashMap;
+import java.util.HashSet;
import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.locks.LockSupport;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.junit.Assert;
import org.junit.Test;
+import com.datastax.driver.core.ResultSet;
+import com.datastax.driver.core.Session;
+import com.datastax.driver.core.SimpleStatement;
+import com.datastax.driver.core.Statement;
+import com.datastax.driver.core.policies.RoundRobinPolicy;
+import org.apache.cassandra.dht.Range;
+import org.apache.cassandra.dht.Token;
import org.apache.cassandra.distributed.Cluster;
import org.apache.cassandra.distributed.api.ConsistencyLevel;
import org.apache.cassandra.distributed.api.ICluster;
import org.apache.cassandra.distributed.api.IInstanceConfig;
+import org.apache.cassandra.distributed.api.IInvokableInstance;
import org.apache.cassandra.distributed.api.TokenSupplier;
+import org.apache.cassandra.distributed.impl.DistributedTestSnitch;
+import org.apache.cassandra.distributed.impl.RowUtil;
import org.apache.cassandra.distributed.shared.NetworkTopology;
+import org.apache.cassandra.locator.EndpointsForRange;
+import org.apache.cassandra.locator.InetAddressAndPort;
+import org.apache.cassandra.service.StorageService;
+import static org.apache.cassandra.distributed.action.GossipHelper.bootstrap;
+import static org.apache.cassandra.distributed.action.GossipHelper.decomission;
+import static org.apache.cassandra.distributed.action.GossipHelper.disseminateGossipState;
+import static org.apache.cassandra.distributed.action.GossipHelper.pullSchemaFrom;
+import static org.apache.cassandra.distributed.action.GossipHelper.statusToBootstrap;
import static org.apache.cassandra.distributed.api.Feature.GOSSIP;
+import static org.apache.cassandra.distributed.api.Feature.NATIVE_PROTOCOL;
import static org.apache.cassandra.distributed.api.Feature.NETWORK;
+import static org.apache.cassandra.distributed.shared.AssertUtils.assertRows;
+import static org.apache.cassandra.distributed.shared.AssertUtils.row;
-// TODO: this test should be removed after running in-jvm dtests is set up via the shared API repository
public class BootstrapTest extends TestBaseImpl
{
-
@Test
public void bootstrapTest() throws Throwable
{
int originalNodeCount = 2;
int expandedNodeCount = originalNodeCount + 1;
- Cluster.Builder builder = builder().withNodes(originalNodeCount)
- .withTokenSupplier(TokenSupplier.evenlyDistributedTokens(expandedNodeCount))
- .withNodeIdTopology(NetworkTopology.singleDcNetworkTopology(expandedNodeCount, "dc0", "rack0"))
- .withConfig(config -> config.with(NETWORK, GOSSIP));
-
- Map<Integer, Long> withBootstrap = null;
- Map<Integer, Long> naturally = null;
- try (Cluster cluster = builder.withNodes(originalNodeCount).start())
+
+ try (Cluster cluster = builder().withNodes(originalNodeCount)
+ .withTokenSupplier(TokenSupplier.evenlyDistributedTokens(expandedNodeCount))
+ .withNodeIdTopology(NetworkTopology.singleDcNetworkTopology(expandedNodeCount, "dc0", "rack0"))
+ .withConfig(config -> config.with(NETWORK, GOSSIP))
+ .start())
{
- populate(cluster);
+ populate(cluster,0, 100);
IInstanceConfig config = cluster.newInstanceConfig();
- config.set("auto_bootstrap", true);
-
- cluster.bootstrap(config).startup();
+ IInvokableInstance newInstance = cluster.initialize(config);
+ withJoinRing(false, () -> newInstance.startup(cluster));
- cluster.stream().forEach(instance -> {
- instance.nodetool("cleanup", KEYSPACE, "tbl");
- });
+ cluster.run(statusToBootstrap(newInstance));
+ cluster.run(pullSchemaFrom(cluster.get(1)), newInstance.config().num());
+ cluster.run(bootstrap(), newInstance.config().num());
- withBootstrap = count(cluster);
+ for (Map.Entry<Integer, Long> e : count(cluster).entrySet())
+ Assert.assertEquals(e.getValue().longValue(), 100L);
Review comment:
can you make it
```
Assert.assertEquals("Node " + e.getKey() + " has incorrect row state", e.getValue().longValue(), 100L);
```
if it fails, would be good to know which node failed.
##########
File path: test/distributed/org/apache/cassandra/distributed/impl/Instance.java
##########
@@ -443,25 +457,31 @@ public void startup(ICluster cluster)
StorageService.instance.registerDaemon(CassandraDaemon.getInstanceForTesting());
if (config.has(GOSSIP))
{
+ MigrationManager.setUptimeFn(() -> System.currentTimeMillis() - startedAt);
Review comment:
note for me:
I double checked the docs `java.lang.management.RuntimeMXBean#getUptime` and see that uptime is relative time in ms, so this logic looks correct (assuming no clock changes).
##########
File path: test/distributed/org/apache/cassandra/distributed/impl/Instance.java
##########
@@ -443,25 +457,31 @@ public void startup(ICluster cluster)
StorageService.instance.registerDaemon(CassandraDaemon.getInstanceForTesting());
if (config.has(GOSSIP))
{
+ MigrationManager.setUptimeFn(() -> System.currentTimeMillis() - startedAt);
StorageService.instance.initServer();
StorageService.instance.removeShutdownHook();
Gossiper.waitToSettle();
}
else
{
- initializeRing(cluster);
- }
+ cluster.stream().forEach(peer -> {
+ // TODO: this isn't going to work for UpgradableCluster
+ GossipHelper.statusToNormal((IInvokableInstance) peer).accept(this);
+ });
- StorageService.instance.ensureTraceKeyspace();
+ }
SystemKeyspace.finishStartup();
CassandraDaemon.getInstanceForTesting().setupCompleted();
if (config.has(NATIVE_PROTOCOL))
{
+ // Start up virtual table support
+ CassandraDaemon.getInstanceForTesting().setupVirtualKeyspaces();
Review comment:
we do this on line 424 already, was there a reason to need it here?
##########
File path: test/distributed/org/apache/cassandra/distributed/test/BootstrapTest.java
##########
@@ -18,85 +18,241 @@
package org.apache.cassandra.distributed.test;
+import java.net.InetSocketAddress;
+import java.time.Duration;
+import java.util.HashMap;
+import java.util.HashSet;
import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.locks.LockSupport;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.junit.Assert;
import org.junit.Test;
+import com.datastax.driver.core.ResultSet;
+import com.datastax.driver.core.Session;
+import com.datastax.driver.core.SimpleStatement;
+import com.datastax.driver.core.Statement;
+import com.datastax.driver.core.policies.RoundRobinPolicy;
+import org.apache.cassandra.dht.Range;
+import org.apache.cassandra.dht.Token;
import org.apache.cassandra.distributed.Cluster;
import org.apache.cassandra.distributed.api.ConsistencyLevel;
import org.apache.cassandra.distributed.api.ICluster;
import org.apache.cassandra.distributed.api.IInstanceConfig;
+import org.apache.cassandra.distributed.api.IInvokableInstance;
import org.apache.cassandra.distributed.api.TokenSupplier;
+import org.apache.cassandra.distributed.impl.DistributedTestSnitch;
+import org.apache.cassandra.distributed.impl.RowUtil;
import org.apache.cassandra.distributed.shared.NetworkTopology;
+import org.apache.cassandra.locator.EndpointsForRange;
+import org.apache.cassandra.locator.InetAddressAndPort;
+import org.apache.cassandra.service.StorageService;
+import static org.apache.cassandra.distributed.action.GossipHelper.bootstrap;
+import static org.apache.cassandra.distributed.action.GossipHelper.decomission;
+import static org.apache.cassandra.distributed.action.GossipHelper.disseminateGossipState;
+import static org.apache.cassandra.distributed.action.GossipHelper.pullSchemaFrom;
+import static org.apache.cassandra.distributed.action.GossipHelper.statusToBootstrap;
import static org.apache.cassandra.distributed.api.Feature.GOSSIP;
+import static org.apache.cassandra.distributed.api.Feature.NATIVE_PROTOCOL;
import static org.apache.cassandra.distributed.api.Feature.NETWORK;
+import static org.apache.cassandra.distributed.shared.AssertUtils.assertRows;
+import static org.apache.cassandra.distributed.shared.AssertUtils.row;
-// TODO: this test should be removed after running in-jvm dtests is set up via the shared API repository
public class BootstrapTest extends TestBaseImpl
{
-
@Test
public void bootstrapTest() throws Throwable
{
int originalNodeCount = 2;
int expandedNodeCount = originalNodeCount + 1;
- Cluster.Builder builder = builder().withNodes(originalNodeCount)
- .withTokenSupplier(TokenSupplier.evenlyDistributedTokens(expandedNodeCount))
- .withNodeIdTopology(NetworkTopology.singleDcNetworkTopology(expandedNodeCount, "dc0", "rack0"))
- .withConfig(config -> config.with(NETWORK, GOSSIP));
-
- Map<Integer, Long> withBootstrap = null;
- Map<Integer, Long> naturally = null;
- try (Cluster cluster = builder.withNodes(originalNodeCount).start())
+
+ try (Cluster cluster = builder().withNodes(originalNodeCount)
+ .withTokenSupplier(TokenSupplier.evenlyDistributedTokens(expandedNodeCount))
+ .withNodeIdTopology(NetworkTopology.singleDcNetworkTopology(expandedNodeCount, "dc0", "rack0"))
+ .withConfig(config -> config.with(NETWORK, GOSSIP))
+ .start())
{
- populate(cluster);
+ populate(cluster,0, 100);
IInstanceConfig config = cluster.newInstanceConfig();
- config.set("auto_bootstrap", true);
-
- cluster.bootstrap(config).startup();
+ IInvokableInstance newInstance = cluster.initialize(config);
+ withJoinRing(false, () -> newInstance.startup(cluster));
- cluster.stream().forEach(instance -> {
- instance.nodetool("cleanup", KEYSPACE, "tbl");
- });
+ cluster.run(statusToBootstrap(newInstance));
+ cluster.run(pullSchemaFrom(cluster.get(1)), newInstance.config().num());
+ cluster.run(bootstrap(), newInstance.config().num());
- withBootstrap = count(cluster);
+ for (Map.Entry<Integer, Long> e : count(cluster).entrySet())
+ Assert.assertEquals(e.getValue().longValue(), 100L);
}
+ }
- builder = builder.withNodes(expandedNodeCount)
- .withTokenSupplier(TokenSupplier.evenlyDistributedTokens(expandedNodeCount))
- .withConfig(config -> config.with(NETWORK, GOSSIP));
+ @Test
+ public void testPendingWrites() throws Throwable
+ {
+ int originalNodeCount = 2;
+ int expandedNodeCount = originalNodeCount + 1;
- try (ICluster cluster = builder.start())
+ try (Cluster cluster = builder().withNodes(originalNodeCount)
+ .withTokenSupplier(TokenSupplier.evenlyDistributedTokens(expandedNodeCount))
+ .withNodeIdTopology(NetworkTopology.singleDcNetworkTopology(expandedNodeCount, "dc0", "rack0"))
+ .withConfig(config -> config.with(NETWORK, GOSSIP))
+ .start())
{
- populate(cluster);
- naturally = count(cluster);
+ populate(cluster, 0, 100);
+ IInstanceConfig config = cluster.newInstanceConfig();
+ IInvokableInstance newInstance = cluster.initialize(config);
+ withJoinRing(false, () -> newInstance.startup(cluster));
+
+ cluster.run(statusToBootstrap(newInstance));
+ cluster.run(bootstrap(false, Duration.ofSeconds(60), Duration.ofSeconds(60)), newInstance.config().num());
+
+ cluster.get(1).acceptsOnInstance((InetSocketAddress ip) -> {
+ Set<InetAddressAndPort> set = new HashSet<>();
+ for (Map.Entry<Range<Token>, EndpointsForRange.Builder> e : StorageService.instance.getTokenMetadata().getPendingRanges(KEYSPACE))
+ {
+ set.addAll(e.getValue().build().endpoints());
+ }
+ Assert.assertEquals(set.size(), 1);
+ Assert.assertTrue(String.format("%s should contain %s", set, ip),
+ set.contains(DistributedTestSnitch.toCassandraInetAddressAndPort(ip)));
+ }).accept(cluster.get(3).broadcastAddress());
+
+ populate(cluster, 100, 150);
+
+ newInstance.nodetoolResult("join").asserts().success();
+
+ cluster.run(disseminateGossipState(newInstance),1, 2);
+
+ cluster.get(1).acceptsOnInstance((InetSocketAddress ip) -> {
+ Set<InetAddressAndPort> set = new HashSet<>();
+ for (Map.Entry<Range<Token>, EndpointsForRange.Builder> e : StorageService.instance.getTokenMetadata().getPendingRanges(KEYSPACE))
+ set.addAll(e.getValue().build().endpoints());
+ assert set.size() == 0 : set;
+ }).accept(cluster.get(3).broadcastAddress());
+
+ for (Map.Entry<Integer, Long> e : count(cluster).entrySet())
+ Assert.assertEquals(e.getValue().longValue(), 150L);
}
+ }
+
+ @Test
+ public void internodeConnectionsDuringDecom() throws Throwable
+ {
+ try (Cluster cluster = builder().withNodes(4)
+ .withConfig(config -> config.with(NETWORK, GOSSIP, NATIVE_PROTOCOL))
+ .start())
+ {
+ populate(cluster, 0, 100);
+
+ cluster.run(decomission(), 1);
- for (Map.Entry<Integer, Long> e : withBootstrap.entrySet())
- Assert.assertTrue(e.getValue() >= naturally.get(e.getKey()));
+ cluster.filters().allVerbs().from(1).messagesMatching((i, i1, iMessage) -> {
+ throw new AssertionError("Decomissioned node should not send any messages");
+ }).drop();
+
+
+ Map<Integer, Long> connectionAttempts = new HashMap<>();
+ long deadline = System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(10);
+
+ // Wait 10 seconds and check if there are any new connection attempts to the decomissioned node
+ while (System.currentTimeMillis() <= deadline)
+ {
+ for (int i = 2; i <= cluster.size(); i++)
+ {
+ Object[][] res = cluster.get(i).executeInternal("SELECT active_connections, connection_attempts FROM system_views.internode_outbound WHERE address = '127.0.0.1' AND port = 7012");
+ Assert.assertEquals(1, res.length);
+ Assert.assertEquals(0L, ((Long) res[0][0]).longValue());
+ long attempts = ((Long) res[0][1]).longValue();
+ if (connectionAttempts.get(i) == null)
+ connectionAttempts.put(i, attempts);
+ else
+ Assert.assertEquals(connectionAttempts.get(i), (Long) attempts);
+ }
+ LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(100));
+ }
+ }
}
- public void populate(ICluster cluster)
+ @Test
+ public void clientConnectionsDuringDecom() throws Throwable
{
- cluster.schemaChange("CREATE KEYSPACE " + KEYSPACE + " WITH replication = {'class': 'SimpleStrategy', 'replication_factor': " + 3 + "};");
- cluster.schemaChange("CREATE TABLE " + KEYSPACE + ".tbl (pk int, ck int, v int, PRIMARY KEY (pk, ck))");
+ ExecutorService executor = Executors.newFixedThreadPool(1);
+ try (Cluster cluster = builder().withNodes(4)
+ .withConfig(config -> config.with(NETWORK, GOSSIP, NATIVE_PROTOCOL))
+ .start())
+ {
+ populate(cluster, 0, 100);
+
+ try (com.datastax.driver.core.Cluster client = com.datastax.driver.core.Cluster.builder().addContactPoint("127.0.0.1")
+ .withLoadBalancingPolicy(new RoundRobinPolicy())
+ .build();
+ Session session = client.connect())
+ {
+ CompletableFuture.runAsync(() -> {
+ while (!Thread.currentThread().isInterrupted())
+ {
+ if (client.getMetadata().getAllHosts().size() == cluster.size())
+ return;
+ LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(100));
+ }
+ }, executor).get(1, TimeUnit.MINUTES);
+
+ cluster.run(decomission(), 1);
+
+ Assert.assertEquals(cluster.size() - 1, client.getMetadata().getAllHosts().size());
Review comment:
I ran this a few times locally and wasn't flaky, but curious how we know this will be stable? I remember the client detecting the connection gets shut down, then runs a callback; what makes sure that the call back completes before this line?
##########
File path: test/distributed/org/apache/cassandra/distributed/impl/AbstractCluster.java
##########
@@ -448,6 +443,22 @@ public int size()
i.config().localRack().equals(rackName));
}
+ public void run(Consumer<I> action) {
Review comment:
we already have `forEach`, rather than adding a new one, can we reuse the existing ones?
##########
File path: src/java/org/apache/cassandra/net/MessagingService.java
##########
@@ -431,6 +431,12 @@ public void shutdown()
public void shutdown(long timeout, TimeUnit units, boolean shutdownGracefully, boolean shutdownExecutors)
{
+ if (isShuttingDown)
Review comment:
I tried doing similar in https://issues.apache.org/jira/browse/CASSANDRA-15968 but remember hitting race condition issues and eventually dropped doing this; I sadly don't remember what the issues were =(
##########
File path: test/distributed/org/apache/cassandra/distributed/impl/Instance.java
##########
@@ -443,25 +457,31 @@ public void startup(ICluster cluster)
StorageService.instance.registerDaemon(CassandraDaemon.getInstanceForTesting());
if (config.has(GOSSIP))
{
+ MigrationManager.setUptimeFn(() -> System.currentTimeMillis() - startedAt);
StorageService.instance.initServer();
StorageService.instance.removeShutdownHook();
Gossiper.waitToSettle();
}
else
{
- initializeRing(cluster);
- }
+ cluster.stream().forEach(peer -> {
+ // TODO: this isn't going to work for UpgradableCluster
+ GossipHelper.statusToNormal((IInvokableInstance) peer).accept(this);
+ });
- StorageService.instance.ensureTraceKeyspace();
+ }
SystemKeyspace.finishStartup();
CassandraDaemon.getInstanceForTesting().setupCompleted();
if (config.has(NATIVE_PROTOCOL))
{
+ // Start up virtual table support
+ CassandraDaemon.getInstanceForTesting().setupVirtualKeyspaces();
CassandraDaemon.getInstanceForTesting().initializeClientTransports();
CassandraDaemon.getInstanceForTesting().start();
+ StorageService.instance.setRpcReady(true);
Review comment:
can you remove, this doesn't match the behavior of CassandraDaemon, by calling start this will be set IFF native transport is enable, so this should be false if native transport isn't enabled.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
[GitHub] [cassandra] ifesdjeen commented on a change in pull request #759: Improve machinery for testing bootstrap and range movements
Posted by GitBox <gi...@apache.org>.
ifesdjeen commented on a change in pull request #759:
URL: https://github.com/apache/cassandra/pull/759#discussion_r504044984
##########
File path: test/distributed/org/apache/cassandra/distributed/action/GossipHelper.java
##########
@@ -0,0 +1,464 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.distributed.action;
+
+
+import java.io.IOException;
+import java.net.InetSocketAddress;
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.TimeUnit;
+import java.util.function.Predicate;
+import java.util.stream.Stream;
+
+import net.openhft.chronicle.core.util.SerializableBiFunction;
+import net.openhft.chronicle.core.util.SerializableConsumer;
+import org.apache.cassandra.db.SystemKeyspace;
+import org.apache.cassandra.dht.IPartitioner;
+import org.apache.cassandra.dht.Token;
+import org.apache.cassandra.distributed.api.ICluster;
+import org.apache.cassandra.distributed.api.IInstance;
+import org.apache.cassandra.distributed.api.IInvokableInstance;
+import org.apache.cassandra.distributed.api.IIsolatedExecutor;
+import org.apache.cassandra.distributed.impl.Instance;
+import org.apache.cassandra.distributed.shared.VersionedApplicationState;
+import org.apache.cassandra.gms.ApplicationState;
+import org.apache.cassandra.gms.EndpointState;
+import org.apache.cassandra.gms.Gossiper;
+import org.apache.cassandra.gms.VersionedValue;
+import org.apache.cassandra.io.util.DataInputBuffer;
+import org.apache.cassandra.io.util.DataOutputBuffer;
+import org.apache.cassandra.locator.InetAddressAndPort;
+import org.apache.cassandra.locator.TokenMetadata;
+import org.apache.cassandra.net.MessagingService;
+import org.apache.cassandra.schema.MigrationManager;
+import org.apache.cassandra.service.PendingRangeCalculatorService;
+import org.apache.cassandra.service.StorageService;
+import org.apache.cassandra.utils.FBUtilities;
+
+import static org.apache.cassandra.distributed.impl.DistributedTestSnitch.toCassandraInetAddressAndPort;
+
+
+public class GossipHelper
+{
+
+ public static ClusterAction clusterAction(InstanceAction action)
Review comment:
Maybe we can do something like this?
```
cluster.run(statusToBootstrap(newInstance));
cluster.run(pullSchemaFrom(cluster.get(1)), newInstance.config().num());
cluster.run(bootstrap(), newInstance.config().num());
```
This could be a good middle ground. You're right that making it all through classes made it look too much like EJB. That said, I still think at least some level of abstraction can be benficial for reuse and making a use of "actions" in Harry: scheduling different clusterwide actions withouot having to write them every time, and being able to reuse them everywhere. WDYT?
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
[GitHub] [cassandra] dcapwell commented on a change in pull request #759: Improve machinery for testing bootstrap and range movements
Posted by GitBox <gi...@apache.org>.
dcapwell commented on a change in pull request #759:
URL: https://github.com/apache/cassandra/pull/759#discussion_r508727995
##########
File path: test/distributed/org/apache/cassandra/distributed/action/GossipHelper.java
##########
@@ -0,0 +1,431 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.distributed.action;
+
+import java.io.IOException;
+import java.io.Serializable;
+import java.net.InetSocketAddress;
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.TimeUnit;
+import java.util.stream.Stream;
+
+import net.openhft.chronicle.core.util.SerializableBiFunction;
+import org.apache.cassandra.db.SystemKeyspace;
+import org.apache.cassandra.dht.IPartitioner;
+import org.apache.cassandra.dht.Token;
+import org.apache.cassandra.distributed.api.IInstance;
+import org.apache.cassandra.distributed.api.IInvokableInstance;
+import org.apache.cassandra.distributed.api.IIsolatedExecutor;
+import org.apache.cassandra.distributed.impl.Instance;
+import org.apache.cassandra.distributed.shared.VersionedApplicationState;
+import org.apache.cassandra.gms.ApplicationState;
+import org.apache.cassandra.gms.EndpointState;
+import org.apache.cassandra.gms.Gossiper;
+import org.apache.cassandra.gms.VersionedValue;
+import org.apache.cassandra.io.util.DataInputBuffer;
+import org.apache.cassandra.io.util.DataOutputBuffer;
+import org.apache.cassandra.locator.InetAddressAndPort;
+import org.apache.cassandra.locator.TokenMetadata;
+import org.apache.cassandra.net.MessagingService;
+import org.apache.cassandra.schema.MigrationManager;
+import org.apache.cassandra.service.PendingRangeCalculatorService;
+import org.apache.cassandra.service.StorageService;
+import org.apache.cassandra.utils.FBUtilities;
+
+import static org.apache.cassandra.distributed.impl.DistributedTestSnitch.toCassandraInetAddressAndPort;
+
+public class GossipHelper
+{
+ public static InstanceAction statusToBootstrap(IInvokableInstance newNode)
+ {
+ return (instance) ->
+ {
+ changeGossipState(instance,
+ newNode,
+ Arrays.asList(tokens(newNode),
+ statusBootstrapping(newNode),
+ statusWithPortBootstrapping(newNode)));
+ };
+ }
+
+ public static InstanceAction statusToNormal(IInvokableInstance peer)
+ {
+ return (target) ->
+ {
+ changeGossipState(target,
+ peer,
+ Arrays.asList(tokens(peer),
+ statusNormal(peer),
+ releaseVersion(peer),
+ statusWithPortNormal(peer)));
+ };
+ }
+
+ /**
+ * This method is unsafe and should be used _only_ when gossip is not used or available: it creates versioned values on the
+ * target instance, which means Gossip versioning gets out of sync. Use a safe couterpart at all times when performing _any_
+ * ring movement operations _or_ if Gossip is used.
+ */
+ public static InstanceAction unsafeStatusToNormal(IInstance peer)
+ {
+ return (target) ->
+ {
+ changeGossipState(target,
+ peer,
+ Arrays.asList(unsafeVersionedToken(target,
+ ApplicationState.TOKENS,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).tokens(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeVersionedToken(target,
+ ApplicationState.STATUS,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeVersionedToken(target,
+ ApplicationState.STATUS_WITH_PORT,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeReleaseVersion(target,
+ peer.config().getString("partitioner"),
+ peer.getReleaseVersionString())));
+ };
+ }
+
+ public static InstanceAction statusToLeaving(IInvokableInstance newNode)
+ {
+ return (instance) -> {
+ changeGossipState(instance,
+ newNode,
+ Arrays.asList(tokens(newNode),
+ statusLeaving(newNode),
+ statusWithPortLeaving(newNode)));
+ };
+ }
+
+ public static InstanceAction bootstrap()
+ {
+ return new BootstrapAction();
+ }
+
+ public static InstanceAction bootstrap(boolean joinRing, Duration waitForBootstrap, Duration waitForSchema)
+ {
+ return new BootstrapAction(joinRing, waitForBootstrap, waitForSchema);
+ }
+
+ public static InstanceAction disseminateGossipState(IInvokableInstance newNode)
+ {
+ return new DisseminateGossipState(newNode);
+ }
+
+ public static InstanceAction pullSchemaFrom(IInvokableInstance pullFrom)
+ {
+ return new PullSchemaFrom(pullFrom);
+ }
+
+ private static InstanceAction disableBinary()
+ {
+ return (instance) -> {
+ instance.runOnInstance(StorageService.instance::stopNativeTransport);
+ };
+ }
+
+ private static class DisseminateGossipState implements InstanceAction
+ {
+ final Map<InetSocketAddress, byte[]> gossipState;
+
+ public DisseminateGossipState(IInvokableInstance... from)
+ {
+ gossipState = new HashMap<>();
+ for (IInvokableInstance node : from)
+ {
+ byte[] epBytes = node.callsOnInstance(() -> {
+ EndpointState epState = Gossiper.instance.getEndpointStateForEndpoint(FBUtilities.getBroadcastAddressAndPort());
Review comment:
I think I found what I was thinking about `org.apache.cassandra.service.StorageService#loadRingState`
```
private void loadRingState()
{
if (Boolean.parseBoolean(System.getProperty("cassandra.load_ring_state", "true")))
{
logger.info("Loading persisted ring state");
Multimap<InetAddressAndPort, Token> loadedTokens = SystemKeyspace.loadTokens();
Map<InetAddressAndPort, UUID> loadedHostIds = SystemKeyspace.loadHostIds();
for (InetAddressAndPort ep : loadedTokens.keySet())
{
if (ep.equals(FBUtilities.getBroadcastAddressAndPort()))
{
// entry has been mistakenly added, delete it
SystemKeyspace.removeEndpoint(ep);
}
else
{
if (loadedHostIds.containsKey(ep))
tokenMetadata.updateHostId(loadedHostIds.get(ep), ep);
Gossiper.runInGossipStageBlocking(() -> Gossiper.instance.addSavedEndpoint(ep, loadedHostIds.get(ep), loadedTokens.get(ep)));
}
}
}
}
```
We remove from peers table, so think I was wrong here.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
[GitHub] [cassandra] ifesdjeen commented on a change in pull request #759: Improve machinery for testing bootstrap and range movements
Posted by GitBox <gi...@apache.org>.
ifesdjeen commented on a change in pull request #759:
URL: https://github.com/apache/cassandra/pull/759#discussion_r508214684
##########
File path: test/distributed/org/apache/cassandra/distributed/action/GossipHelper.java
##########
@@ -0,0 +1,431 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.distributed.action;
+
+import java.io.IOException;
+import java.io.Serializable;
+import java.net.InetSocketAddress;
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.TimeUnit;
+import java.util.stream.Stream;
+
+import net.openhft.chronicle.core.util.SerializableBiFunction;
+import org.apache.cassandra.db.SystemKeyspace;
+import org.apache.cassandra.dht.IPartitioner;
+import org.apache.cassandra.dht.Token;
+import org.apache.cassandra.distributed.api.IInstance;
+import org.apache.cassandra.distributed.api.IInvokableInstance;
+import org.apache.cassandra.distributed.api.IIsolatedExecutor;
+import org.apache.cassandra.distributed.impl.Instance;
+import org.apache.cassandra.distributed.shared.VersionedApplicationState;
+import org.apache.cassandra.gms.ApplicationState;
+import org.apache.cassandra.gms.EndpointState;
+import org.apache.cassandra.gms.Gossiper;
+import org.apache.cassandra.gms.VersionedValue;
+import org.apache.cassandra.io.util.DataInputBuffer;
+import org.apache.cassandra.io.util.DataOutputBuffer;
+import org.apache.cassandra.locator.InetAddressAndPort;
+import org.apache.cassandra.locator.TokenMetadata;
+import org.apache.cassandra.net.MessagingService;
+import org.apache.cassandra.schema.MigrationManager;
+import org.apache.cassandra.service.PendingRangeCalculatorService;
+import org.apache.cassandra.service.StorageService;
+import org.apache.cassandra.utils.FBUtilities;
+
+import static org.apache.cassandra.distributed.impl.DistributedTestSnitch.toCassandraInetAddressAndPort;
+
+public class GossipHelper
+{
+ public static InstanceAction statusToBootstrap(IInvokableInstance newNode)
+ {
+ return (instance) ->
+ {
+ changeGossipState(instance,
+ newNode,
+ Arrays.asList(tokens(newNode),
+ statusBootstrapping(newNode),
+ statusWithPortBootstrapping(newNode)));
+ };
+ }
+
+ public static InstanceAction statusToNormal(IInvokableInstance peer)
+ {
+ return (target) ->
+ {
+ changeGossipState(target,
+ peer,
+ Arrays.asList(tokens(peer),
+ statusNormal(peer),
+ releaseVersion(peer),
+ statusWithPortNormal(peer)));
+ };
+ }
+
+ /**
+ * This method is unsafe and should be used _only_ when gossip is not used or available: it creates versioned values on the
+ * target instance, which means Gossip versioning gets out of sync. Use a safe couterpart at all times when performing _any_
+ * ring movement operations _or_ if Gossip is used.
+ */
+ public static InstanceAction unsafeStatusToNormal(IInstance peer)
+ {
+ return (target) ->
+ {
+ changeGossipState(target,
+ peer,
+ Arrays.asList(unsafeVersionedToken(target,
+ ApplicationState.TOKENS,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).tokens(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeVersionedToken(target,
+ ApplicationState.STATUS,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeVersionedToken(target,
+ ApplicationState.STATUS_WITH_PORT,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeReleaseVersion(target,
+ peer.config().getString("partitioner"),
+ peer.getReleaseVersionString())));
+ };
+ }
+
+ public static InstanceAction statusToLeaving(IInvokableInstance newNode)
+ {
+ return (instance) -> {
+ changeGossipState(instance,
+ newNode,
+ Arrays.asList(tokens(newNode),
+ statusLeaving(newNode),
+ statusWithPortLeaving(newNode)));
+ };
+ }
+
+ public static InstanceAction bootstrap()
+ {
+ return new BootstrapAction();
+ }
+
+ public static InstanceAction bootstrap(boolean joinRing, Duration waitForBootstrap, Duration waitForSchema)
+ {
+ return new BootstrapAction(joinRing, waitForBootstrap, waitForSchema);
+ }
+
+ public static InstanceAction disseminateGossipState(IInvokableInstance newNode)
+ {
+ return new DisseminateGossipState(newNode);
+ }
+
+ public static InstanceAction pullSchemaFrom(IInvokableInstance pullFrom)
+ {
+ return new PullSchemaFrom(pullFrom);
+ }
+
+ private static InstanceAction disableBinary()
+ {
+ return (instance) -> {
+ instance.runOnInstance(StorageService.instance::stopNativeTransport);
+ };
+ }
+
+ private static class DisseminateGossipState implements InstanceAction
+ {
+ final Map<InetSocketAddress, byte[]> gossipState;
+
+ public DisseminateGossipState(IInvokableInstance... from)
+ {
+ gossipState = new HashMap<>();
+ for (IInvokableInstance node : from)
+ {
+ byte[] epBytes = node.callsOnInstance(() -> {
+ EndpointState epState = Gossiper.instance.getEndpointStateForEndpoint(FBUtilities.getBroadcastAddressAndPort());
+ return toBytes(epState);
+ }).call();
+ gossipState.put(node.broadcastAddress(), epBytes);
+ }
+ }
+
+ public void accept(IInvokableInstance instance)
+ {
+ instance.appliesOnInstance((IIsolatedExecutor.SerializableFunction<Map<InetSocketAddress, byte[]>, Void>)
+ (map) -> {
+ Map<InetAddressAndPort, EndpointState> newState = new HashMap<>();
+ for (Map.Entry<InetSocketAddress, byte[]> e : map.entrySet())
+ newState.put(toCassandraInetAddressAndPort(e.getKey()), fromBytes(e.getValue()));
+
+ Gossiper.runInGossipStageBlocking(() -> {
+ Gossiper.instance.applyStateLocally(newState);
+ });
+ return null;
+ }).apply(gossipState);
+ }
+ }
+
+ public static byte[] toBytes(EndpointState epState)
+ {
+ try (DataOutputBuffer out = new DataOutputBuffer(1024))
+ {
+ EndpointState.serializer.serialize(epState, out, MessagingService.current_version);
+ return out.toByteArray();
+ }
+ catch (IOException e)
+ {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public static EndpointState fromBytes(byte[] bytes)
Review comment:
👍 switched to private
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
[GitHub] [cassandra] emersonrocha85 commented on pull request #759: Improve machinery for testing bootstrap and range movements
Posted by GitBox <gi...@apache.org>.
emersonrocha85 commented on pull request #759:
URL: https://github.com/apache/cassandra/pull/759#issuecomment-712218816
Thanks!
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
[GitHub] [cassandra] ifesdjeen commented on a change in pull request #759: Improve machinery for testing bootstrap and range movements
Posted by GitBox <gi...@apache.org>.
ifesdjeen commented on a change in pull request #759:
URL: https://github.com/apache/cassandra/pull/759#discussion_r505392898
##########
File path: README.asc
##########
@@ -1,3 +1,4 @@
+
Review comment:
It'll go away on commit
##########
File path: test/distributed/org/apache/cassandra/distributed/test/BootstrapTest.java
##########
@@ -18,85 +18,241 @@
package org.apache.cassandra.distributed.test;
+import java.net.InetSocketAddress;
+import java.time.Duration;
+import java.util.HashMap;
+import java.util.HashSet;
import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.locks.LockSupport;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.junit.Assert;
import org.junit.Test;
+import com.datastax.driver.core.ResultSet;
+import com.datastax.driver.core.Session;
+import com.datastax.driver.core.SimpleStatement;
+import com.datastax.driver.core.Statement;
+import com.datastax.driver.core.policies.RoundRobinPolicy;
+import org.apache.cassandra.dht.Range;
+import org.apache.cassandra.dht.Token;
import org.apache.cassandra.distributed.Cluster;
import org.apache.cassandra.distributed.api.ConsistencyLevel;
import org.apache.cassandra.distributed.api.ICluster;
import org.apache.cassandra.distributed.api.IInstanceConfig;
+import org.apache.cassandra.distributed.api.IInvokableInstance;
import org.apache.cassandra.distributed.api.TokenSupplier;
+import org.apache.cassandra.distributed.impl.DistributedTestSnitch;
+import org.apache.cassandra.distributed.impl.RowUtil;
import org.apache.cassandra.distributed.shared.NetworkTopology;
+import org.apache.cassandra.locator.EndpointsForRange;
+import org.apache.cassandra.locator.InetAddressAndPort;
+import org.apache.cassandra.service.StorageService;
+import static org.apache.cassandra.distributed.action.GossipHelper.bootstrap;
+import static org.apache.cassandra.distributed.action.GossipHelper.decomission;
+import static org.apache.cassandra.distributed.action.GossipHelper.disseminateGossipState;
+import static org.apache.cassandra.distributed.action.GossipHelper.pullSchemaFrom;
+import static org.apache.cassandra.distributed.action.GossipHelper.statusToBootstrap;
import static org.apache.cassandra.distributed.api.Feature.GOSSIP;
+import static org.apache.cassandra.distributed.api.Feature.NATIVE_PROTOCOL;
import static org.apache.cassandra.distributed.api.Feature.NETWORK;
+import static org.apache.cassandra.distributed.shared.AssertUtils.assertRows;
+import static org.apache.cassandra.distributed.shared.AssertUtils.row;
-// TODO: this test should be removed after running in-jvm dtests is set up via the shared API repository
public class BootstrapTest extends TestBaseImpl
{
-
@Test
public void bootstrapTest() throws Throwable
{
int originalNodeCount = 2;
int expandedNodeCount = originalNodeCount + 1;
- Cluster.Builder builder = builder().withNodes(originalNodeCount)
- .withTokenSupplier(TokenSupplier.evenlyDistributedTokens(expandedNodeCount))
- .withNodeIdTopology(NetworkTopology.singleDcNetworkTopology(expandedNodeCount, "dc0", "rack0"))
- .withConfig(config -> config.with(NETWORK, GOSSIP));
-
- Map<Integer, Long> withBootstrap = null;
- Map<Integer, Long> naturally = null;
- try (Cluster cluster = builder.withNodes(originalNodeCount).start())
+
+ try (Cluster cluster = builder().withNodes(originalNodeCount)
+ .withTokenSupplier(TokenSupplier.evenlyDistributedTokens(expandedNodeCount))
+ .withNodeIdTopology(NetworkTopology.singleDcNetworkTopology(expandedNodeCount, "dc0", "rack0"))
+ .withConfig(config -> config.with(NETWORK, GOSSIP))
+ .start())
{
- populate(cluster);
+ populate(cluster,0, 100);
IInstanceConfig config = cluster.newInstanceConfig();
- config.set("auto_bootstrap", true);
-
- cluster.bootstrap(config).startup();
+ IInvokableInstance newInstance = cluster.initialize(config);
+ withJoinRing(false, () -> newInstance.startup(cluster));
- cluster.stream().forEach(instance -> {
- instance.nodetool("cleanup", KEYSPACE, "tbl");
- });
+ cluster.run(statusToBootstrap(newInstance));
+ cluster.run(pullSchemaFrom(cluster.get(1)), newInstance.config().num());
+ cluster.run(bootstrap(), newInstance.config().num());
- withBootstrap = count(cluster);
+ for (Map.Entry<Integer, Long> e : count(cluster).entrySet())
+ Assert.assertEquals(e.getValue().longValue(), 100L);
}
+ }
- builder = builder.withNodes(expandedNodeCount)
- .withTokenSupplier(TokenSupplier.evenlyDistributedTokens(expandedNodeCount))
- .withConfig(config -> config.with(NETWORK, GOSSIP));
+ @Test
+ public void testPendingWrites() throws Throwable
+ {
+ int originalNodeCount = 2;
+ int expandedNodeCount = originalNodeCount + 1;
- try (ICluster cluster = builder.start())
+ try (Cluster cluster = builder().withNodes(originalNodeCount)
+ .withTokenSupplier(TokenSupplier.evenlyDistributedTokens(expandedNodeCount))
+ .withNodeIdTopology(NetworkTopology.singleDcNetworkTopology(expandedNodeCount, "dc0", "rack0"))
+ .withConfig(config -> config.with(NETWORK, GOSSIP))
+ .start())
{
- populate(cluster);
- naturally = count(cluster);
+ populate(cluster, 0, 100);
+ IInstanceConfig config = cluster.newInstanceConfig();
+ IInvokableInstance newInstance = cluster.initialize(config);
+ withJoinRing(false, () -> newInstance.startup(cluster));
+
+ cluster.run(statusToBootstrap(newInstance));
+ cluster.run(bootstrap(false, Duration.ofSeconds(60), Duration.ofSeconds(60)), newInstance.config().num());
Review comment:
I've added the missing setting bootstrap state.
Since the intent of this specific test is not to test `joinTokenRing`, but rather to test side-effects of joining: pending ranges, I decided to opt-out for a smaller bootstrap action. In general, the intention of this patch is to be able to reproduce arbitrary cluster states. For example, a state when streaming has finished, but node hasn't yet joined the ring. By opting to `auto_bootstrap`, we're losing this level of control.
I understand there is more than one way to implement this, and using Byteman can be one of the ways, but in this particular case it's not the one I think is approprate.
To reiterate, the purpose of this whole patch is exactly to be able to produce such states, and I think your Byteman example shows that the patch has achieved this. If you like, I can include your test as well; however, I do not think it's necessary, since we now have an easier way to do the same.
##########
File path: test/distributed/org/apache/cassandra/distributed/test/BootstrapTest.java
##########
@@ -18,85 +18,241 @@
package org.apache.cassandra.distributed.test;
+import java.net.InetSocketAddress;
+import java.time.Duration;
+import java.util.HashMap;
+import java.util.HashSet;
import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.locks.LockSupport;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.junit.Assert;
import org.junit.Test;
+import com.datastax.driver.core.ResultSet;
+import com.datastax.driver.core.Session;
+import com.datastax.driver.core.SimpleStatement;
+import com.datastax.driver.core.Statement;
+import com.datastax.driver.core.policies.RoundRobinPolicy;
+import org.apache.cassandra.dht.Range;
+import org.apache.cassandra.dht.Token;
import org.apache.cassandra.distributed.Cluster;
import org.apache.cassandra.distributed.api.ConsistencyLevel;
import org.apache.cassandra.distributed.api.ICluster;
import org.apache.cassandra.distributed.api.IInstanceConfig;
+import org.apache.cassandra.distributed.api.IInvokableInstance;
import org.apache.cassandra.distributed.api.TokenSupplier;
+import org.apache.cassandra.distributed.impl.DistributedTestSnitch;
+import org.apache.cassandra.distributed.impl.RowUtil;
import org.apache.cassandra.distributed.shared.NetworkTopology;
+import org.apache.cassandra.locator.EndpointsForRange;
+import org.apache.cassandra.locator.InetAddressAndPort;
+import org.apache.cassandra.service.StorageService;
+import static org.apache.cassandra.distributed.action.GossipHelper.bootstrap;
+import static org.apache.cassandra.distributed.action.GossipHelper.decomission;
+import static org.apache.cassandra.distributed.action.GossipHelper.disseminateGossipState;
+import static org.apache.cassandra.distributed.action.GossipHelper.pullSchemaFrom;
+import static org.apache.cassandra.distributed.action.GossipHelper.statusToBootstrap;
import static org.apache.cassandra.distributed.api.Feature.GOSSIP;
+import static org.apache.cassandra.distributed.api.Feature.NATIVE_PROTOCOL;
import static org.apache.cassandra.distributed.api.Feature.NETWORK;
+import static org.apache.cassandra.distributed.shared.AssertUtils.assertRows;
+import static org.apache.cassandra.distributed.shared.AssertUtils.row;
-// TODO: this test should be removed after running in-jvm dtests is set up via the shared API repository
public class BootstrapTest extends TestBaseImpl
{
-
@Test
public void bootstrapTest() throws Throwable
{
int originalNodeCount = 2;
int expandedNodeCount = originalNodeCount + 1;
- Cluster.Builder builder = builder().withNodes(originalNodeCount)
- .withTokenSupplier(TokenSupplier.evenlyDistributedTokens(expandedNodeCount))
- .withNodeIdTopology(NetworkTopology.singleDcNetworkTopology(expandedNodeCount, "dc0", "rack0"))
- .withConfig(config -> config.with(NETWORK, GOSSIP));
-
- Map<Integer, Long> withBootstrap = null;
- Map<Integer, Long> naturally = null;
- try (Cluster cluster = builder.withNodes(originalNodeCount).start())
+
+ try (Cluster cluster = builder().withNodes(originalNodeCount)
+ .withTokenSupplier(TokenSupplier.evenlyDistributedTokens(expandedNodeCount))
+ .withNodeIdTopology(NetworkTopology.singleDcNetworkTopology(expandedNodeCount, "dc0", "rack0"))
+ .withConfig(config -> config.with(NETWORK, GOSSIP))
+ .start())
{
- populate(cluster);
+ populate(cluster,0, 100);
IInstanceConfig config = cluster.newInstanceConfig();
- config.set("auto_bootstrap", true);
-
- cluster.bootstrap(config).startup();
+ IInvokableInstance newInstance = cluster.initialize(config);
+ withJoinRing(false, () -> newInstance.startup(cluster));
- cluster.stream().forEach(instance -> {
- instance.nodetool("cleanup", KEYSPACE, "tbl");
- });
+ cluster.run(statusToBootstrap(newInstance));
+ cluster.run(pullSchemaFrom(cluster.get(1)), newInstance.config().num());
+ cluster.run(bootstrap(), newInstance.config().num());
- withBootstrap = count(cluster);
+ for (Map.Entry<Integer, Long> e : count(cluster).entrySet())
+ Assert.assertEquals(e.getValue().longValue(), 100L);
Review comment:
done
##########
File path: src/java/org/apache/cassandra/service/LoadBroadcaster.java
##########
@@ -87,6 +87,8 @@ public void startBroadcasting()
{
public void run()
{
+ if (!Gossiper.instance.isEnabled())
Review comment:
since this is not a part of this patch, this will be done in a corresponding related patch.
##########
File path: test/distributed/org/apache/cassandra/distributed/test/BootstrapTest.java
##########
@@ -18,85 +18,244 @@
package org.apache.cassandra.distributed.test;
+import java.net.InetSocketAddress;
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.HashSet;
import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.locks.LockSupport;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.junit.Assert;
import org.junit.Test;
+import com.datastax.driver.core.ResultSet;
+import com.datastax.driver.core.Session;
+import com.datastax.driver.core.SimpleStatement;
+import com.datastax.driver.core.Statement;
+import com.datastax.driver.core.policies.RoundRobinPolicy;
+import org.apache.cassandra.dht.Range;
+import org.apache.cassandra.dht.Token;
import org.apache.cassandra.distributed.Cluster;
import org.apache.cassandra.distributed.api.ConsistencyLevel;
import org.apache.cassandra.distributed.api.ICluster;
import org.apache.cassandra.distributed.api.IInstanceConfig;
+import org.apache.cassandra.distributed.api.IInvokableInstance;
import org.apache.cassandra.distributed.api.TokenSupplier;
+import org.apache.cassandra.distributed.impl.DistributedTestSnitch;
+import org.apache.cassandra.distributed.impl.RowUtil;
import org.apache.cassandra.distributed.shared.NetworkTopology;
+import org.apache.cassandra.locator.EndpointsForRange;
+import org.apache.cassandra.locator.InetAddressAndPort;
+import org.apache.cassandra.service.StorageService;
+import static java.util.Arrays.*;
+import static org.apache.cassandra.distributed.action.GossipHelper.bootstrap;
+import static org.apache.cassandra.distributed.action.GossipHelper.decomission;
+import static org.apache.cassandra.distributed.action.GossipHelper.disseminateGossipState;
+import static org.apache.cassandra.distributed.action.GossipHelper.pullSchemaFrom;
+import static org.apache.cassandra.distributed.action.GossipHelper.statusToBootstrap;
import static org.apache.cassandra.distributed.api.Feature.GOSSIP;
+import static org.apache.cassandra.distributed.api.Feature.NATIVE_PROTOCOL;
import static org.apache.cassandra.distributed.api.Feature.NETWORK;
+import static org.apache.cassandra.distributed.shared.AssertUtils.assertRows;
+import static org.apache.cassandra.distributed.shared.AssertUtils.row;
-// TODO: this test should be removed after running in-jvm dtests is set up via the shared API repository
public class BootstrapTest extends TestBaseImpl
{
-
@Test
public void bootstrapTest() throws Throwable
{
int originalNodeCount = 2;
int expandedNodeCount = originalNodeCount + 1;
- Cluster.Builder builder = builder().withNodes(originalNodeCount)
- .withTokenSupplier(TokenSupplier.evenlyDistributedTokens(expandedNodeCount))
- .withNodeIdTopology(NetworkTopology.singleDcNetworkTopology(expandedNodeCount, "dc0", "rack0"))
- .withConfig(config -> config.with(NETWORK, GOSSIP));
-
- Map<Integer, Long> withBootstrap = null;
- Map<Integer, Long> naturally = null;
- try (Cluster cluster = builder.withNodes(originalNodeCount).start())
+
+ try (Cluster cluster = builder().withNodes(originalNodeCount)
+ .withTokenSupplier(TokenSupplier.evenlyDistributedTokens(expandedNodeCount))
+ .withNodeIdTopology(NetworkTopology.singleDcNetworkTopology(expandedNodeCount, "dc0", "rack0"))
+ .withConfig(config -> config.with(NETWORK, GOSSIP))
+ .start())
{
- populate(cluster);
+ populate(cluster,0, 100);
IInstanceConfig config = cluster.newInstanceConfig();
- config.set("auto_bootstrap", true);
-
- cluster.bootstrap(config).startup();
+ IInvokableInstance newInstance = cluster.initialize(config);
+ withJoinRing(false, () -> newInstance.startup(cluster));
- cluster.stream().forEach(instance -> {
- instance.nodetool("cleanup", KEYSPACE, "tbl");
- });
+ cluster.forEach(statusToBootstrap(newInstance));
+ cluster.run(asList(pullSchemaFrom(cluster.get(1)),
Review comment:
Since the purpose of this patch is to introduce machinery to move cluster through arbitrary series of steps, I believe the test serves its purpose, since we'll need reliable runnable `bootstrap` and `pullSchemaFrom` for Harry. I've added the test you've implemented as `autoBootstrapTest`.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
[GitHub] [cassandra] ifesdjeen commented on a change in pull request #759: Improve machinery for testing bootstrap and range movements
Posted by GitBox <gi...@apache.org>.
ifesdjeen commented on a change in pull request #759:
URL: https://github.com/apache/cassandra/pull/759#discussion_r507832180
##########
File path: test/distributed/org/apache/cassandra/distributed/action/GossipHelper.java
##########
@@ -0,0 +1,437 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.distributed.action;
+
+import java.io.IOException;
+import java.io.Serializable;
+import java.net.InetSocketAddress;
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.TimeUnit;
+import java.util.function.Predicate;
+import java.util.stream.Stream;
+
+import net.openhft.chronicle.core.util.SerializableBiFunction;
+import net.openhft.chronicle.core.util.SerializableConsumer;
+import org.apache.cassandra.db.SystemKeyspace;
+import org.apache.cassandra.dht.IPartitioner;
+import org.apache.cassandra.dht.Token;
+import org.apache.cassandra.distributed.Cluster;
+import org.apache.cassandra.distributed.api.ICluster;
+import org.apache.cassandra.distributed.api.IInstance;
+import org.apache.cassandra.distributed.api.IInvokableInstance;
+import org.apache.cassandra.distributed.api.IIsolatedExecutor;
+import org.apache.cassandra.distributed.impl.Instance;
+import org.apache.cassandra.distributed.shared.VersionedApplicationState;
+import org.apache.cassandra.gms.ApplicationState;
+import org.apache.cassandra.gms.EndpointState;
+import org.apache.cassandra.gms.Gossiper;
+import org.apache.cassandra.gms.VersionedValue;
+import org.apache.cassandra.io.util.DataInputBuffer;
+import org.apache.cassandra.io.util.DataOutputBuffer;
+import org.apache.cassandra.locator.InetAddressAndPort;
+import org.apache.cassandra.locator.TokenMetadata;
+import org.apache.cassandra.net.MessagingService;
+import org.apache.cassandra.schema.MigrationManager;
+import org.apache.cassandra.service.PendingRangeCalculatorService;
+import org.apache.cassandra.service.StorageService;
+import org.apache.cassandra.utils.FBUtilities;
+
+import static org.apache.cassandra.distributed.impl.DistributedTestSnitch.toCassandraInetAddressAndPort;
+
+public class GossipHelper
+{
+ public static InstanceAction statusToBootstrap(IInvokableInstance newNode)
+ {
+ return (instance) ->
+ {
+ changeGossipState(instance,
+ newNode,
+ Arrays.asList(tokens(newNode),
+ statusBootstrapping(newNode),
+ statusWithPortBootstrapping(newNode)));
+ };
+ }
+
+ public static InstanceAction statusToNormal(IInvokableInstance peer)
+ {
+ return (target) ->
+ {
+ changeGossipState(target,
+ peer,
+ Arrays.asList(tokens(peer),
+ statusNormal(peer),
+ releaseVersion(peer),
+ statusWithPortNormal(peer)));
+ };
+ }
+
+ /**
+ * This method is unsafe and should be used _only_ when gossip is not used or available: it creates versioned values on the
+ * target instance, which means Gossip versioning gets out of sync. Use a safe couterpart at all times when performing _any_
+ * ring movement operations _or_ if Gossip is used.
+ */
+ public static InstanceAction unsafeStatusToNormal(IInstance peer)
+ {
+ return (target) ->
+ {
+ changeGossipState(target,
+ peer,
+ Arrays.asList(unsafeVersionedToken(target,
+ ApplicationState.TOKENS,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).tokens(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeVersionedToken(target,
+ ApplicationState.STATUS,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeVersionedToken(target,
+ ApplicationState.STATUS_WITH_PORT,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsaveReleaseVersion(target,
+ peer.config().getString("partitioner"),
+ peer.getReleaseVersionString())));
+ };
+ }
+
+ public static InstanceAction statusToLeaving(IInvokableInstance newNode)
+ {
+ return (instance) -> {
+ changeGossipState(instance,
+ newNode,
+ Arrays.asList(tokens(newNode),
+ statusLeaving(newNode),
+ statusWithPortLeaving(newNode)));
+ };
+ }
+
+ public static InstanceAction bootstrap()
+ {
+ return new BootstrapAction();
+ }
+
+ public static InstanceAction bootstrap(boolean joinRing, Duration waitForBootstrap, Duration waitForSchema)
+ {
+ return new BootstrapAction(joinRing, waitForBootstrap, waitForSchema);
+ }
+
+ public static InstanceAction disseminateGossipState(IInvokableInstance newNode)
+ {
+ return new DisseminateGossipState(newNode);
+ }
+
+ public static InstanceAction pullSchemaFrom(IInvokableInstance pullFrom)
+ {
+ return new PullSchemaFrom(pullFrom);
+ }
+
+ private static InstanceAction disableBinary()
+ {
+ return (instance) -> {
+ instance.runOnInstance(() -> {
+ StorageService.instance.stopNativeTransport();
+ });
+ };
+ };
+
+ private static class DisseminateGossipState implements InstanceAction
+ {
+ final Map<InetSocketAddress, byte[]> gossipState;
+
+ public DisseminateGossipState(IInvokableInstance... from)
+ {
+ gossipState = new HashMap<>();
+ for (IInvokableInstance node : from)
+ {
+ byte[] epBytes = node.callsOnInstance(() -> {
+ EndpointState epState = Gossiper.instance.getEndpointStateForEndpoint(FBUtilities.getBroadcastAddressAndPort());
+ return toBytes(epState);
+ }).call();
+ gossipState.put(node.broadcastAddress(), epBytes);
+ }
+ }
+
+ public void accept(IInvokableInstance instance)
+ {
+ instance.appliesOnInstance((IIsolatedExecutor.SerializableFunction<Map<InetSocketAddress, byte[]>, Void>)
+ (map) -> {
+ Map<InetAddressAndPort, EndpointState> newState = new HashMap<>();
+ for (Map.Entry<InetSocketAddress, byte[]> e : map.entrySet())
+ newState.put(toCassandraInetAddressAndPort(e.getKey()), fromBytes(e.getValue()));
+
+ Gossiper.runInGossipStageBlocking(() -> {
+ Gossiper.instance.applyStateLocally(newState);
+ });
+ return null;
+ }).apply(gossipState);
+ }
+ }
+
+ public static byte[] toBytes(EndpointState epState)
+ {
+ try (DataOutputBuffer out = new DataOutputBuffer(1024))
+ {
+ EndpointState.serializer.serialize(epState, out, MessagingService.current_version);
+ return out.toByteArray();
+ }
+ catch (IOException e)
+ {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public static EndpointState fromBytes(byte[] bytes)
+ {
+ try (DataInputBuffer in = new DataInputBuffer(bytes))
+ {
+ return EndpointState.serializer.deserialize(in, MessagingService.current_version);
+ }
+ catch (Throwable t)
+ {
+ throw new RuntimeException(t);
+ }
+ }
+
+ private static class PullSchemaFrom implements InstanceAction
+ {
+ final InetSocketAddress pullFrom;
+
+ public PullSchemaFrom(IInvokableInstance pullFrom)
+ {
+ this.pullFrom = pullFrom.broadcastAddress();;
+ }
+
+ public void accept(IInvokableInstance pullTo)
+ {
+ pullTo.acceptsOnInstance((InetSocketAddress pullFrom) -> {
+ InetAddressAndPort endpoint = toCassandraInetAddressAndPort(pullFrom);
+ EndpointState state = Gossiper.instance.getEndpointStateForEndpoint(endpoint);
+ MigrationManager.scheduleSchemaPull(endpoint, state);
+ MigrationManager.waitUntilReadyForBootstrap();
+ }).accept(pullFrom);
+ }
+ }
+
+ private static class BootstrapAction implements InstanceAction, Serializable
+ {
+ private final boolean joinRing;
+ private final Duration waitForBootstrap;
+ private final Duration waitForSchema;
+
+ public BootstrapAction()
+ {
+ this(true, Duration.ofMinutes(10), Duration.ofSeconds(10));
+ }
+
+ public BootstrapAction(boolean joinRing, Duration waitForBootstrap, Duration waitForSchema)
+ {
+ this.joinRing = joinRing;
+ this.waitForBootstrap = waitForBootstrap;
+ this.waitForSchema = waitForSchema;
+ }
+
+ public void accept(IInvokableInstance instance)
+ {
+ instance.appliesOnInstance((String partitionerString, String tokenString) -> {
+ IPartitioner partitioner = FBUtilities.newPartitioner(partitionerString);
+ List<Token> tokens = Collections.singletonList(partitioner.getTokenFactory().fromString(tokenString));
+ try
+ {
+ SystemKeyspace.setBootstrapState(SystemKeyspace.BootstrapState.IN_PROGRESS);
+ StorageService.instance.waitForSchema((int) waitForSchema.toMillis());
+ PendingRangeCalculatorService.instance.blockUntilFinished();
+ StorageService.instance.startBootstrap(tokens).get(waitForBootstrap.toMillis(), TimeUnit.MILLISECONDS);
+ StorageService.instance.setUpDistributedSystemKeyspaces();
+ if (joinRing)
+ StorageService.instance.finishJoiningRing(true, tokens);
+ }
+ catch (Throwable t)
+ {
+ throw new RuntimeException(t);
+ }
+
+ return null;
+ }).apply(instance.config().getString("partitioner"), instance.config().getString("initial_token"));
+ }
+ }
+
+ public static InstanceAction decomission()
+ {
+ return (target) -> {
+ target.runOnInstance(() -> {
+ try
+ {
+ StorageService.instance.decommission(false);
+ }
+ catch (InterruptedException e)
+ {
+ throw new RuntimeException();
+ }
+ });
+ };
+ }
+
+
+ public static VersionedApplicationState tokens(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.TOKENS, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).tokens(tokens));
+ }
+
+ public static VersionedApplicationState unsaveReleaseVersion(IInvokableInstance instance, String partitionerStr, String releaseVersionStr)
Review comment:
Oh. Thanks for spotting! Not sure how I haven't seen this one...
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
[GitHub] [cassandra] iamaleksey commented on a change in pull request #759: Improve machinery for testing bootstrap and range movements
Posted by GitBox <gi...@apache.org>.
iamaleksey commented on a change in pull request #759:
URL: https://github.com/apache/cassandra/pull/759#discussion_r507756425
##########
File path: src/java/org/apache/cassandra/service/StorageService.java
##########
@@ -1107,7 +1109,7 @@ private void executePreJoinTasks(boolean bootstrap)
.forEach(cfs -> cfs.indexManager.executePreJoinTasksBlocking(bootstrap));
}
- private void finishJoiningRing(boolean didBootstrap, Collection<Token> tokens)
+ public void finishJoiningRing(boolean didBootstrap, Collection<Token> tokens)
Review comment:
Nit: mark with `@VisibleForTesting`?
##########
File path: test/distributed/org/apache/cassandra/distributed/impl/AbstractCluster.java
##########
@@ -448,6 +444,33 @@ public int size()
i.config().localRack().equals(rackName));
}
+ public void run(Consumer<? super I> action, Predicate<I> filter) {
Review comment:
Nit: brace on the same line
##########
File path: test/distributed/org/apache/cassandra/distributed/impl/AbstractCluster.java
##########
@@ -448,6 +444,33 @@ public int size()
i.config().localRack().equals(rackName));
}
+ public void run(Consumer<? super I> action, Predicate<I> filter) {
+ run(Collections.singletonList(action), filter);
+ }
+
+ public void run(Collection<Consumer<? super I>> actions, Predicate<I> filter) {
+ stream().forEach(instance -> {
+ for (Consumer<? super I> action : actions)
+ {
+ if (filter.test(instance))
+ action.accept(instance);
+ }
+
+ });
+ }
+
+ public void run(Consumer<? super I> action, int... instanceIds) {
+ run(Collections.singletonList(action), instanceIds);
+ }
+
+ public void run(List<Consumer<? super I>> actions, int... instanceIds) {
Review comment:
Nit: ditto
##########
File path: test/distributed/org/apache/cassandra/distributed/impl/AbstractCluster.java
##########
@@ -448,6 +444,33 @@ public int size()
i.config().localRack().equals(rackName));
}
+ public void run(Consumer<? super I> action, Predicate<I> filter) {
+ run(Collections.singletonList(action), filter);
+ }
+
+ public void run(Collection<Consumer<? super I>> actions, Predicate<I> filter) {
Review comment:
Nit: brace on the same line
##########
File path: test/distributed/org/apache/cassandra/distributed/impl/AbstractCluster.java
##########
@@ -448,6 +444,33 @@ public int size()
i.config().localRack().equals(rackName));
}
+ public void run(Consumer<? super I> action, Predicate<I> filter) {
+ run(Collections.singletonList(action), filter);
+ }
+
+ public void run(Collection<Consumer<? super I>> actions, Predicate<I> filter) {
+ stream().forEach(instance -> {
+ for (Consumer<? super I> action : actions)
+ {
+ if (filter.test(instance))
+ action.accept(instance);
+ }
+
+ });
+ }
+
+ public void run(Consumer<? super I> action, int... instanceIds) {
Review comment:
Nit: ditto
##########
File path: test/distributed/org/apache/cassandra/distributed/action/GossipHelper.java
##########
@@ -0,0 +1,437 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.distributed.action;
+
+import java.io.IOException;
+import java.io.Serializable;
+import java.net.InetSocketAddress;
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.TimeUnit;
+import java.util.function.Predicate;
Review comment:
Nit: a bunch of unused imports
##########
File path: test/distributed/org/apache/cassandra/distributed/action/GossipHelper.java
##########
@@ -0,0 +1,437 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.distributed.action;
+
+import java.io.IOException;
+import java.io.Serializable;
+import java.net.InetSocketAddress;
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.TimeUnit;
+import java.util.function.Predicate;
+import java.util.stream.Stream;
+
+import net.openhft.chronicle.core.util.SerializableBiFunction;
+import net.openhft.chronicle.core.util.SerializableConsumer;
+import org.apache.cassandra.db.SystemKeyspace;
+import org.apache.cassandra.dht.IPartitioner;
+import org.apache.cassandra.dht.Token;
+import org.apache.cassandra.distributed.Cluster;
+import org.apache.cassandra.distributed.api.ICluster;
+import org.apache.cassandra.distributed.api.IInstance;
+import org.apache.cassandra.distributed.api.IInvokableInstance;
+import org.apache.cassandra.distributed.api.IIsolatedExecutor;
+import org.apache.cassandra.distributed.impl.Instance;
+import org.apache.cassandra.distributed.shared.VersionedApplicationState;
+import org.apache.cassandra.gms.ApplicationState;
+import org.apache.cassandra.gms.EndpointState;
+import org.apache.cassandra.gms.Gossiper;
+import org.apache.cassandra.gms.VersionedValue;
+import org.apache.cassandra.io.util.DataInputBuffer;
+import org.apache.cassandra.io.util.DataOutputBuffer;
+import org.apache.cassandra.locator.InetAddressAndPort;
+import org.apache.cassandra.locator.TokenMetadata;
+import org.apache.cassandra.net.MessagingService;
+import org.apache.cassandra.schema.MigrationManager;
+import org.apache.cassandra.service.PendingRangeCalculatorService;
+import org.apache.cassandra.service.StorageService;
+import org.apache.cassandra.utils.FBUtilities;
+
+import static org.apache.cassandra.distributed.impl.DistributedTestSnitch.toCassandraInetAddressAndPort;
+
+public class GossipHelper
+{
+ public static InstanceAction statusToBootstrap(IInvokableInstance newNode)
+ {
+ return (instance) ->
+ {
+ changeGossipState(instance,
+ newNode,
+ Arrays.asList(tokens(newNode),
+ statusBootstrapping(newNode),
+ statusWithPortBootstrapping(newNode)));
+ };
+ }
+
+ public static InstanceAction statusToNormal(IInvokableInstance peer)
+ {
+ return (target) ->
+ {
+ changeGossipState(target,
+ peer,
+ Arrays.asList(tokens(peer),
+ statusNormal(peer),
+ releaseVersion(peer),
+ statusWithPortNormal(peer)));
+ };
+ }
+
+ /**
+ * This method is unsafe and should be used _only_ when gossip is not used or available: it creates versioned values on the
+ * target instance, which means Gossip versioning gets out of sync. Use a safe couterpart at all times when performing _any_
+ * ring movement operations _or_ if Gossip is used.
+ */
+ public static InstanceAction unsafeStatusToNormal(IInstance peer)
+ {
+ return (target) ->
+ {
+ changeGossipState(target,
+ peer,
+ Arrays.asList(unsafeVersionedToken(target,
+ ApplicationState.TOKENS,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).tokens(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeVersionedToken(target,
+ ApplicationState.STATUS,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeVersionedToken(target,
+ ApplicationState.STATUS_WITH_PORT,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsaveReleaseVersion(target,
+ peer.config().getString("partitioner"),
+ peer.getReleaseVersionString())));
+ };
+ }
+
+ public static InstanceAction statusToLeaving(IInvokableInstance newNode)
+ {
+ return (instance) -> {
+ changeGossipState(instance,
+ newNode,
+ Arrays.asList(tokens(newNode),
+ statusLeaving(newNode),
+ statusWithPortLeaving(newNode)));
+ };
+ }
+
+ public static InstanceAction bootstrap()
+ {
+ return new BootstrapAction();
+ }
+
+ public static InstanceAction bootstrap(boolean joinRing, Duration waitForBootstrap, Duration waitForSchema)
+ {
+ return new BootstrapAction(joinRing, waitForBootstrap, waitForSchema);
+ }
+
+ public static InstanceAction disseminateGossipState(IInvokableInstance newNode)
+ {
+ return new DisseminateGossipState(newNode);
+ }
+
+ public static InstanceAction pullSchemaFrom(IInvokableInstance pullFrom)
+ {
+ return new PullSchemaFrom(pullFrom);
+ }
+
+ private static InstanceAction disableBinary()
+ {
+ return (instance) -> {
+ instance.runOnInstance(() -> {
+ StorageService.instance.stopNativeTransport();
+ });
+ };
+ };
+
+ private static class DisseminateGossipState implements InstanceAction
+ {
+ final Map<InetSocketAddress, byte[]> gossipState;
+
+ public DisseminateGossipState(IInvokableInstance... from)
+ {
+ gossipState = new HashMap<>();
+ for (IInvokableInstance node : from)
+ {
+ byte[] epBytes = node.callsOnInstance(() -> {
+ EndpointState epState = Gossiper.instance.getEndpointStateForEndpoint(FBUtilities.getBroadcastAddressAndPort());
+ return toBytes(epState);
+ }).call();
+ gossipState.put(node.broadcastAddress(), epBytes);
+ }
+ }
+
+ public void accept(IInvokableInstance instance)
+ {
+ instance.appliesOnInstance((IIsolatedExecutor.SerializableFunction<Map<InetSocketAddress, byte[]>, Void>)
+ (map) -> {
+ Map<InetAddressAndPort, EndpointState> newState = new HashMap<>();
+ for (Map.Entry<InetSocketAddress, byte[]> e : map.entrySet())
+ newState.put(toCassandraInetAddressAndPort(e.getKey()), fromBytes(e.getValue()));
+
+ Gossiper.runInGossipStageBlocking(() -> {
+ Gossiper.instance.applyStateLocally(newState);
+ });
+ return null;
+ }).apply(gossipState);
+ }
+ }
+
+ public static byte[] toBytes(EndpointState epState)
+ {
+ try (DataOutputBuffer out = new DataOutputBuffer(1024))
+ {
+ EndpointState.serializer.serialize(epState, out, MessagingService.current_version);
+ return out.toByteArray();
+ }
+ catch (IOException e)
+ {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public static EndpointState fromBytes(byte[] bytes)
+ {
+ try (DataInputBuffer in = new DataInputBuffer(bytes))
+ {
+ return EndpointState.serializer.deserialize(in, MessagingService.current_version);
+ }
+ catch (Throwable t)
+ {
+ throw new RuntimeException(t);
+ }
+ }
+
+ private static class PullSchemaFrom implements InstanceAction
+ {
+ final InetSocketAddress pullFrom;
+
+ public PullSchemaFrom(IInvokableInstance pullFrom)
+ {
+ this.pullFrom = pullFrom.broadcastAddress();;
+ }
+
+ public void accept(IInvokableInstance pullTo)
+ {
+ pullTo.acceptsOnInstance((InetSocketAddress pullFrom) -> {
+ InetAddressAndPort endpoint = toCassandraInetAddressAndPort(pullFrom);
+ EndpointState state = Gossiper.instance.getEndpointStateForEndpoint(endpoint);
+ MigrationManager.scheduleSchemaPull(endpoint, state);
+ MigrationManager.waitUntilReadyForBootstrap();
+ }).accept(pullFrom);
+ }
+ }
+
+ private static class BootstrapAction implements InstanceAction, Serializable
+ {
+ private final boolean joinRing;
+ private final Duration waitForBootstrap;
+ private final Duration waitForSchema;
+
+ public BootstrapAction()
+ {
+ this(true, Duration.ofMinutes(10), Duration.ofSeconds(10));
+ }
+
+ public BootstrapAction(boolean joinRing, Duration waitForBootstrap, Duration waitForSchema)
+ {
+ this.joinRing = joinRing;
+ this.waitForBootstrap = waitForBootstrap;
+ this.waitForSchema = waitForSchema;
+ }
+
+ public void accept(IInvokableInstance instance)
+ {
+ instance.appliesOnInstance((String partitionerString, String tokenString) -> {
+ IPartitioner partitioner = FBUtilities.newPartitioner(partitionerString);
+ List<Token> tokens = Collections.singletonList(partitioner.getTokenFactory().fromString(tokenString));
+ try
+ {
+ SystemKeyspace.setBootstrapState(SystemKeyspace.BootstrapState.IN_PROGRESS);
+ StorageService.instance.waitForSchema((int) waitForSchema.toMillis());
+ PendingRangeCalculatorService.instance.blockUntilFinished();
+ StorageService.instance.startBootstrap(tokens).get(waitForBootstrap.toMillis(), TimeUnit.MILLISECONDS);
+ StorageService.instance.setUpDistributedSystemKeyspaces();
+ if (joinRing)
+ StorageService.instance.finishJoiningRing(true, tokens);
+ }
+ catch (Throwable t)
+ {
+ throw new RuntimeException(t);
+ }
+
+ return null;
+ }).apply(instance.config().getString("partitioner"), instance.config().getString("initial_token"));
+ }
+ }
+
+ public static InstanceAction decomission()
+ {
+ return (target) -> {
+ target.runOnInstance(() -> {
+ try
+ {
+ StorageService.instance.decommission(false);
+ }
+ catch (InterruptedException e)
+ {
+ throw new RuntimeException();
+ }
+ });
+ };
+ }
+
+
+ public static VersionedApplicationState tokens(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.TOKENS, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).tokens(tokens));
+ }
+
+ public static VersionedApplicationState unsaveReleaseVersion(IInvokableInstance instance, String partitionerStr, String releaseVersionStr)
Review comment:
Typo - unsave?
##########
File path: test/distributed/org/apache/cassandra/distributed/action/GossipHelper.java
##########
@@ -0,0 +1,437 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.distributed.action;
+
+import java.io.IOException;
+import java.io.Serializable;
+import java.net.InetSocketAddress;
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.TimeUnit;
+import java.util.function.Predicate;
+import java.util.stream.Stream;
+
+import net.openhft.chronicle.core.util.SerializableBiFunction;
+import net.openhft.chronicle.core.util.SerializableConsumer;
+import org.apache.cassandra.db.SystemKeyspace;
+import org.apache.cassandra.dht.IPartitioner;
+import org.apache.cassandra.dht.Token;
+import org.apache.cassandra.distributed.Cluster;
+import org.apache.cassandra.distributed.api.ICluster;
+import org.apache.cassandra.distributed.api.IInstance;
+import org.apache.cassandra.distributed.api.IInvokableInstance;
+import org.apache.cassandra.distributed.api.IIsolatedExecutor;
+import org.apache.cassandra.distributed.impl.Instance;
+import org.apache.cassandra.distributed.shared.VersionedApplicationState;
+import org.apache.cassandra.gms.ApplicationState;
+import org.apache.cassandra.gms.EndpointState;
+import org.apache.cassandra.gms.Gossiper;
+import org.apache.cassandra.gms.VersionedValue;
+import org.apache.cassandra.io.util.DataInputBuffer;
+import org.apache.cassandra.io.util.DataOutputBuffer;
+import org.apache.cassandra.locator.InetAddressAndPort;
+import org.apache.cassandra.locator.TokenMetadata;
+import org.apache.cassandra.net.MessagingService;
+import org.apache.cassandra.schema.MigrationManager;
+import org.apache.cassandra.service.PendingRangeCalculatorService;
+import org.apache.cassandra.service.StorageService;
+import org.apache.cassandra.utils.FBUtilities;
+
+import static org.apache.cassandra.distributed.impl.DistributedTestSnitch.toCassandraInetAddressAndPort;
+
+public class GossipHelper
+{
+ public static InstanceAction statusToBootstrap(IInvokableInstance newNode)
+ {
+ return (instance) ->
+ {
+ changeGossipState(instance,
+ newNode,
+ Arrays.asList(tokens(newNode),
+ statusBootstrapping(newNode),
+ statusWithPortBootstrapping(newNode)));
+ };
+ }
+
+ public static InstanceAction statusToNormal(IInvokableInstance peer)
+ {
+ return (target) ->
+ {
+ changeGossipState(target,
+ peer,
+ Arrays.asList(tokens(peer),
+ statusNormal(peer),
+ releaseVersion(peer),
+ statusWithPortNormal(peer)));
+ };
+ }
+
+ /**
+ * This method is unsafe and should be used _only_ when gossip is not used or available: it creates versioned values on the
+ * target instance, which means Gossip versioning gets out of sync. Use a safe couterpart at all times when performing _any_
+ * ring movement operations _or_ if Gossip is used.
+ */
+ public static InstanceAction unsafeStatusToNormal(IInstance peer)
+ {
+ return (target) ->
+ {
+ changeGossipState(target,
+ peer,
+ Arrays.asList(unsafeVersionedToken(target,
+ ApplicationState.TOKENS,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).tokens(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeVersionedToken(target,
+ ApplicationState.STATUS,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeVersionedToken(target,
+ ApplicationState.STATUS_WITH_PORT,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsaveReleaseVersion(target,
+ peer.config().getString("partitioner"),
+ peer.getReleaseVersionString())));
+ };
+ }
+
+ public static InstanceAction statusToLeaving(IInvokableInstance newNode)
+ {
+ return (instance) -> {
+ changeGossipState(instance,
+ newNode,
+ Arrays.asList(tokens(newNode),
+ statusLeaving(newNode),
+ statusWithPortLeaving(newNode)));
+ };
+ }
+
+ public static InstanceAction bootstrap()
+ {
+ return new BootstrapAction();
+ }
+
+ public static InstanceAction bootstrap(boolean joinRing, Duration waitForBootstrap, Duration waitForSchema)
+ {
+ return new BootstrapAction(joinRing, waitForBootstrap, waitForSchema);
+ }
+
+ public static InstanceAction disseminateGossipState(IInvokableInstance newNode)
+ {
+ return new DisseminateGossipState(newNode);
+ }
+
+ public static InstanceAction pullSchemaFrom(IInvokableInstance pullFrom)
+ {
+ return new PullSchemaFrom(pullFrom);
+ }
+
+ private static InstanceAction disableBinary()
+ {
+ return (instance) -> {
+ instance.runOnInstance(() -> {
+ StorageService.instance.stopNativeTransport();
+ });
+ };
+ };
Review comment:
Nit: redundant semicolon, and lambda above can be replaced with a method reference.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
[GitHub] [cassandra] ifesdjeen commented on a change in pull request #759: Improve machinery for testing bootstrap and range movements
Posted by GitBox <gi...@apache.org>.
ifesdjeen commented on a change in pull request #759:
URL: https://github.com/apache/cassandra/pull/759#discussion_r508273163
##########
File path: test/distributed/org/apache/cassandra/distributed/action/GossipHelper.java
##########
@@ -0,0 +1,431 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.distributed.action;
+
+import java.io.IOException;
+import java.io.Serializable;
+import java.net.InetSocketAddress;
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.TimeUnit;
+import java.util.stream.Stream;
+
+import net.openhft.chronicle.core.util.SerializableBiFunction;
+import org.apache.cassandra.db.SystemKeyspace;
+import org.apache.cassandra.dht.IPartitioner;
+import org.apache.cassandra.dht.Token;
+import org.apache.cassandra.distributed.api.IInstance;
+import org.apache.cassandra.distributed.api.IInvokableInstance;
+import org.apache.cassandra.distributed.api.IIsolatedExecutor;
+import org.apache.cassandra.distributed.impl.Instance;
+import org.apache.cassandra.distributed.shared.VersionedApplicationState;
+import org.apache.cassandra.gms.ApplicationState;
+import org.apache.cassandra.gms.EndpointState;
+import org.apache.cassandra.gms.Gossiper;
+import org.apache.cassandra.gms.VersionedValue;
+import org.apache.cassandra.io.util.DataInputBuffer;
+import org.apache.cassandra.io.util.DataOutputBuffer;
+import org.apache.cassandra.locator.InetAddressAndPort;
+import org.apache.cassandra.locator.TokenMetadata;
+import org.apache.cassandra.net.MessagingService;
+import org.apache.cassandra.schema.MigrationManager;
+import org.apache.cassandra.service.PendingRangeCalculatorService;
+import org.apache.cassandra.service.StorageService;
+import org.apache.cassandra.utils.FBUtilities;
+
+import static org.apache.cassandra.distributed.impl.DistributedTestSnitch.toCassandraInetAddressAndPort;
+
+public class GossipHelper
+{
+ public static InstanceAction statusToBootstrap(IInvokableInstance newNode)
+ {
+ return (instance) ->
+ {
+ changeGossipState(instance,
+ newNode,
+ Arrays.asList(tokens(newNode),
+ statusBootstrapping(newNode),
+ statusWithPortBootstrapping(newNode)));
+ };
+ }
+
+ public static InstanceAction statusToNormal(IInvokableInstance peer)
+ {
+ return (target) ->
+ {
+ changeGossipState(target,
+ peer,
+ Arrays.asList(tokens(peer),
+ statusNormal(peer),
+ releaseVersion(peer),
+ statusWithPortNormal(peer)));
+ };
+ }
+
+ /**
+ * This method is unsafe and should be used _only_ when gossip is not used or available: it creates versioned values on the
+ * target instance, which means Gossip versioning gets out of sync. Use a safe couterpart at all times when performing _any_
+ * ring movement operations _or_ if Gossip is used.
+ */
+ public static InstanceAction unsafeStatusToNormal(IInstance peer)
+ {
+ return (target) ->
+ {
+ changeGossipState(target,
+ peer,
+ Arrays.asList(unsafeVersionedToken(target,
+ ApplicationState.TOKENS,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).tokens(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeVersionedToken(target,
+ ApplicationState.STATUS,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeVersionedToken(target,
+ ApplicationState.STATUS_WITH_PORT,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeReleaseVersion(target,
+ peer.config().getString("partitioner"),
+ peer.getReleaseVersionString())));
+ };
+ }
+
+ public static InstanceAction statusToLeaving(IInvokableInstance newNode)
+ {
+ return (instance) -> {
+ changeGossipState(instance,
+ newNode,
+ Arrays.asList(tokens(newNode),
+ statusLeaving(newNode),
+ statusWithPortLeaving(newNode)));
+ };
+ }
+
+ public static InstanceAction bootstrap()
+ {
+ return new BootstrapAction();
+ }
+
+ public static InstanceAction bootstrap(boolean joinRing, Duration waitForBootstrap, Duration waitForSchema)
+ {
+ return new BootstrapAction(joinRing, waitForBootstrap, waitForSchema);
+ }
+
+ public static InstanceAction disseminateGossipState(IInvokableInstance newNode)
+ {
+ return new DisseminateGossipState(newNode);
+ }
+
+ public static InstanceAction pullSchemaFrom(IInvokableInstance pullFrom)
+ {
+ return new PullSchemaFrom(pullFrom);
+ }
+
+ private static InstanceAction disableBinary()
+ {
+ return (instance) -> {
+ instance.runOnInstance(StorageService.instance::stopNativeTransport);
+ };
+ }
+
+ private static class DisseminateGossipState implements InstanceAction
+ {
+ final Map<InetSocketAddress, byte[]> gossipState;
+
+ public DisseminateGossipState(IInvokableInstance... from)
+ {
+ gossipState = new HashMap<>();
+ for (IInvokableInstance node : from)
+ {
+ byte[] epBytes = node.callsOnInstance(() -> {
+ EndpointState epState = Gossiper.instance.getEndpointStateForEndpoint(FBUtilities.getBroadcastAddressAndPort());
+ return toBytes(epState);
+ }).call();
+ gossipState.put(node.broadcastAddress(), epBytes);
+ }
+ }
+
+ public void accept(IInvokableInstance instance)
+ {
+ instance.appliesOnInstance((IIsolatedExecutor.SerializableFunction<Map<InetSocketAddress, byte[]>, Void>)
+ (map) -> {
+ Map<InetAddressAndPort, EndpointState> newState = new HashMap<>();
+ for (Map.Entry<InetSocketAddress, byte[]> e : map.entrySet())
+ newState.put(toCassandraInetAddressAndPort(e.getKey()), fromBytes(e.getValue()));
+
+ Gossiper.runInGossipStageBlocking(() -> {
+ Gossiper.instance.applyStateLocally(newState);
+ });
+ return null;
+ }).apply(gossipState);
+ }
+ }
+
+ public static byte[] toBytes(EndpointState epState)
+ {
+ try (DataOutputBuffer out = new DataOutputBuffer(1024))
+ {
+ EndpointState.serializer.serialize(epState, out, MessagingService.current_version);
+ return out.toByteArray();
+ }
+ catch (IOException e)
+ {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public static EndpointState fromBytes(byte[] bytes)
+ {
+ try (DataInputBuffer in = new DataInputBuffer(bytes))
+ {
+ return EndpointState.serializer.deserialize(in, MessagingService.current_version);
+ }
+ catch (Throwable t)
+ {
+ throw new RuntimeException(t);
+ }
+ }
+
+ private static class PullSchemaFrom implements InstanceAction
+ {
+ final InetSocketAddress pullFrom;
+
+ public PullSchemaFrom(IInvokableInstance pullFrom)
+ {
+ this.pullFrom = pullFrom.broadcastAddress();;
+ }
+
+ public void accept(IInvokableInstance pullTo)
+ {
+ pullTo.acceptsOnInstance((InetSocketAddress pullFrom) -> {
+ InetAddressAndPort endpoint = toCassandraInetAddressAndPort(pullFrom);
+ EndpointState state = Gossiper.instance.getEndpointStateForEndpoint(endpoint);
+ MigrationManager.scheduleSchemaPull(endpoint, state);
+ MigrationManager.waitUntilReadyForBootstrap();
+ }).accept(pullFrom);
+ }
+ }
+
+ private static class BootstrapAction implements InstanceAction, Serializable
+ {
+ private final boolean joinRing;
+ private final Duration waitForBootstrap;
+ private final Duration waitForSchema;
+
+ public BootstrapAction()
+ {
+ this(true, Duration.ofMinutes(10), Duration.ofSeconds(10));
+ }
+
+ public BootstrapAction(boolean joinRing, Duration waitForBootstrap, Duration waitForSchema)
+ {
+ this.joinRing = joinRing;
+ this.waitForBootstrap = waitForBootstrap;
+ this.waitForSchema = waitForSchema;
+ }
+
+ public void accept(IInvokableInstance instance)
+ {
+ instance.appliesOnInstance((String partitionerString, String tokenString) -> {
+ IPartitioner partitioner = FBUtilities.newPartitioner(partitionerString);
+ List<Token> tokens = Collections.singletonList(partitioner.getTokenFactory().fromString(tokenString));
+ try
+ {
+ SystemKeyspace.setBootstrapState(SystemKeyspace.BootstrapState.IN_PROGRESS);
+ StorageService.instance.waitForSchema((int) waitForSchema.toMillis());
+ PendingRangeCalculatorService.instance.blockUntilFinished();
+ StorageService.instance.startBootstrap(tokens).get(waitForBootstrap.toMillis(), TimeUnit.MILLISECONDS);
+ StorageService.instance.setUpDistributedSystemKeyspaces();
+ if (joinRing)
+ StorageService.instance.finishJoiningRing(true, tokens);
+ }
+ catch (Throwable t)
+ {
+ throw new RuntimeException(t);
+ }
+
+ return null;
+ }).apply(instance.config().getString("partitioner"), instance.config().getString("initial_token"));
+ }
+ }
+
+ public static InstanceAction decomission()
+ {
+ return (target) -> {
+ target.runOnInstance(() -> {
+ try
+ {
+ StorageService.instance.decommission(false);
+ }
+ catch (InterruptedException e)
+ {
+ throw new RuntimeException();
+ }
+ });
+ };
+ }
+
+
+ public static VersionedApplicationState tokens(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.TOKENS, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).tokens(tokens));
+ }
+
+ public static VersionedApplicationState unsafeReleaseVersion(IInvokableInstance instance, String partitionerStr, String releaseVersionStr)
+ {
+ return instance.appliesOnInstance((String partitionerString, String releaseVersion) -> {
+ IPartitioner partitioner = FBUtilities.newPartitioner(partitionerString);
+ VersionedValue versionedValue = new VersionedValue.VersionedValueFactory(partitioner).releaseVersion(releaseVersion);
+ return new VersionedApplicationState(ApplicationState.RELEASE_VERSION.ordinal(), versionedValue.value, versionedValue.version);
+ }).apply(partitionerStr, releaseVersionStr);
+ }
+
+ public static VersionedApplicationState releaseVersion(IInvokableInstance instance)
+ {
+ return unsafeReleaseVersion(instance, instance.config().getString("partitioner"), instance.getReleaseVersionString());
+ }
+
+ public static VersionedApplicationState statusNormal(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens));
+ }
+
+ public static VersionedApplicationState statusWithPortNormal(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS_WITH_PORT, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens));
+ }
+
+ public static VersionedApplicationState statusBootstrapping(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).bootstrapping(tokens));
+ }
+
+ public static VersionedApplicationState statusWithPortBootstrapping(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS_WITH_PORT, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).bootstrapping(tokens));
+ }
+
+ public static VersionedApplicationState statusLeaving(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).leaving(tokens));
+ }
+
+ public static VersionedApplicationState statusWithPortLeaving(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS_WITH_PORT, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).leaving(tokens));
+ }
+
+ public static VersionedValue toVersionedValue(VersionedApplicationState vv)
+ {
+ return VersionedValue.unsafeMakeVersionedValue(vv.value, vv.version);
+ }
+
+ public static ApplicationState toApplicationState(VersionedApplicationState vv)
+ {
+ return ApplicationState.values()[vv.applicationState];
+ }
+
+ public static VersionedApplicationState unsafeVersionedToken(IInvokableInstance instance,
+ ApplicationState applicationState,
+ SerializableBiFunction<IPartitioner, Collection<Token>, VersionedValue> supplier,
+ String partitionerStr, String initialTokenStr)
+ {
+ return instance.appliesOnInstance((String partitionerString, String tokenString) -> {
+ IPartitioner partitioner = FBUtilities.newPartitioner(partitionerString);
+ Token token = partitioner.getTokenFactory().fromString(tokenString);
+
+ VersionedValue versionedValue = supplier.apply(partitioner, Collections.singleton(token));
+ return new VersionedApplicationState(applicationState.ordinal(), versionedValue.value, versionedValue.version);
+ }).apply(partitionerStr, initialTokenStr);
+ }
+
+ public static VersionedApplicationState versionedToken(IInvokableInstance instance, ApplicationState applicationState, SerializableBiFunction<IPartitioner, Collection<Token>, VersionedValue> supplier)
+ {
+ return unsafeVersionedToken(instance, applicationState, supplier, instance.config().getString("partitioner"), instance.config().getString("initial_token"));
+ }
+
+ public void removeFromRing(IInstance peer)
+ {
+ InetAddressAndPort endpoint = toCassandraInetAddressAndPort(peer.broadcastAddress());
+
+ TokenMetadata tokenMetadata = StorageService.instance.getTokenMetadata();
+ tokenMetadata.removeEndpoint(endpoint);
+ Collection<Token> tokens = tokenMetadata.getTokens(endpoint);
+ if (!tokens.isEmpty())
+ tokenMetadata.removeBootstrapTokens(tokens);
+
+ Gossiper.runInGossipStageBlocking(() -> Gossiper.instance.unsafeAnulEndpoint(endpoint));
+
+ SystemKeyspace.removeEndpoint(endpoint);
+ PendingRangeCalculatorService.instance.update();
+ PendingRangeCalculatorService.instance.blockUntilFinished();
+ }
+
+ public static void changeGossipState(Stream<IInvokableInstance> targets, Instance peer, List<VersionedApplicationState> newState)
+ {
+ targets.forEach((instance) -> {
+ changeGossipState(instance, peer, newState);
+ });
+ }
+
+ /**
+ * Changes gossip state of the `peer` on `target`
+ */
+ public static void changeGossipState(IInvokableInstance target, IInstance peer, List<VersionedApplicationState> newState)
+ {
+ int version = peer.isShutdown() ? MessagingService.current_version : peer.getMessagingVersion();
+
+ target.appliesOnInstance((InetSocketAddress addr, UUID hostId, Integer messagingVersion) -> {
+ InetAddressAndPort endpoint = toCassandraInetAddressAndPort(addr);
+ StorageService storageService = StorageService.instance;
+
+ Gossiper.runInGossipStageBlocking(() -> {
+ EndpointState state = Gossiper.instance.getEndpointStateForEndpoint(endpoint);
+ if (state == null)
+ {
+ Gossiper.instance.initializeNodeUnsafe(endpoint, hostId, 1);
+ state = Gossiper.instance.getEndpointStateForEndpoint(endpoint);
+ if (state.isAlive() && !Gossiper.instance.isDeadState(state))
+ Gossiper.instance.realMarkAlive(endpoint, state);
+ }
+
+ for (VersionedApplicationState value : newState)
+ {
+ ApplicationState as = toApplicationState(value);
+ VersionedValue vv = toVersionedValue(value);
+ state.addApplicationState(as, vv);
+ storageService.onChange(endpoint, as, vv);
+ }
+ });
+
+ MessagingService.instance().versions.set(endpoint, messagingVersion);
Review comment:
Sure, makes sense. Switched and removed.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
[GitHub] [cassandra] dcapwell commented on a change in pull request #759: Improve machinery for testing bootstrap and range movements
Posted by GitBox <gi...@apache.org>.
dcapwell commented on a change in pull request #759:
URL: https://github.com/apache/cassandra/pull/759#discussion_r503601390
##########
File path: test/distributed/org/apache/cassandra/distributed/impl/Instance.java
##########
@@ -438,24 +457,27 @@ public void startup(ICluster cluster)
// TODO: this is more than just gossip
if (config.has(GOSSIP))
{
- StorageService.instance.initServer();
+ StorageService.instance.registerDaemon(CassandraDaemon.getInstanceForTesting());
+ StorageService.instance.initServer(StorageService.RING_DELAY,
+ !startupOptions.contains(StartupOption.SKIP_RING_JOIN));
Review comment:
this is an addition to the API, why not leverage the config api we have already? `joinRing` is already defined as
```
private static final boolean joinRing = Boolean.parseBoolean(System.getProperty("cassandra.join_ring", "true"));
```
so it mostly highlights that we want the ability to override system properties in isolation (a test I just added called this out as well); so rather than adding a new interface API into jvm-dtest, what about leveraging the config API?
This also addresses ring delay, which is defined as
```
private static int getRingDelay()
{
String newdelay = System.getProperty("cassandra.ring_delay_ms");
if (newdelay != null)
{
logger.info("Overriding RING_DELAY to {}ms", newdelay);
return Integer.parseInt(newdelay);
}
else
return 30 * 1000;
}
```
##########
File path: test/distributed/org/apache/cassandra/distributed/impl/Instance.java
##########
@@ -438,24 +457,27 @@ public void startup(ICluster cluster)
// TODO: this is more than just gossip
if (config.has(GOSSIP))
{
- StorageService.instance.initServer();
+ StorageService.instance.registerDaemon(CassandraDaemon.getInstanceForTesting());
Review comment:
FYI if you rebase this already exists in each branch.
##########
File path: test/distributed/org/apache/cassandra/distributed/impl/Instance.java
##########
@@ -438,24 +457,27 @@ public void startup(ICluster cluster)
// TODO: this is more than just gossip
if (config.has(GOSSIP))
{
- StorageService.instance.initServer();
+ StorageService.instance.registerDaemon(CassandraDaemon.getInstanceForTesting());
+ StorageService.instance.initServer(StorageService.RING_DELAY,
+ !startupOptions.contains(StartupOption.SKIP_RING_JOIN));
StorageService.instance.removeShutdownHook();
Gossiper.waitToSettle();
}
- else
+ else if (!startupOptions.contains(StartupOption.SKIP_RING_JOIN))
{
- initializeRing(cluster);
- }
+ cluster.stream().forEach(peer -> {
Review comment:
this doesn't look to match the `cassandra.join_ring` property, why do we mock out the ring if we ask to skip joining the ring?
What I see is now, if you ask to not join the ring we only setup gossip to know about this instance
```
Collection<Token> tokens = SystemKeyspace.getSavedTokens();
if (!tokens.isEmpty())
{
tokenMetadata.updateNormalTokens(tokens, FBUtilities.getBroadcastAddressAndPort());
// order is important here, the gossiper can fire in between adding these two states. It's ok to send TOKENS without STATUS, but *not* vice versa.
List<Pair<ApplicationState, VersionedValue>> states = new ArrayList<Pair<ApplicationState, VersionedValue>>();
states.add(Pair.create(ApplicationState.TOKENS, valueFactory.tokens(tokens)));
states.add(Pair.create(ApplicationState.STATUS_WITH_PORT, valueFactory.hibernate(true)));
states.add(Pair.create(ApplicationState.STATUS, valueFactory.hibernate(true)));
Gossiper.instance.addLocalApplicationStates(states);
}
doAuthSetup(true);
```
so feel that we should keep this behavior here as well, so should only do our mocking of the ring when gossip isn't enabled.
##########
File path: test/distributed/org/apache/cassandra/distributed/impl/IsolatedExecutor.java
##########
@@ -139,6 +139,10 @@
private static <E extends Serializable> E transferOneObject(E object, ClassLoader classLoader, Method deserializeOnInstance)
{
+ // already the right object
+ if (object.getClass().getClassLoader() == classLoader)
Review comment:
if the lambda is in the class loader, then do we know all objects it touches are also in the class loader?
##########
File path: test/distributed/org/apache/cassandra/distributed/action/GossipHelper.java
##########
@@ -0,0 +1,464 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.distributed.action;
+
+
+import java.io.IOException;
+import java.net.InetSocketAddress;
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.TimeUnit;
+import java.util.function.Predicate;
+import java.util.stream.Stream;
+
+import net.openhft.chronicle.core.util.SerializableBiFunction;
+import net.openhft.chronicle.core.util.SerializableConsumer;
+import org.apache.cassandra.db.SystemKeyspace;
+import org.apache.cassandra.dht.IPartitioner;
+import org.apache.cassandra.dht.Token;
+import org.apache.cassandra.distributed.api.ICluster;
+import org.apache.cassandra.distributed.api.IInstance;
+import org.apache.cassandra.distributed.api.IInvokableInstance;
+import org.apache.cassandra.distributed.api.IIsolatedExecutor;
+import org.apache.cassandra.distributed.impl.Instance;
+import org.apache.cassandra.distributed.shared.VersionedApplicationState;
+import org.apache.cassandra.gms.ApplicationState;
+import org.apache.cassandra.gms.EndpointState;
+import org.apache.cassandra.gms.Gossiper;
+import org.apache.cassandra.gms.VersionedValue;
+import org.apache.cassandra.io.util.DataInputBuffer;
+import org.apache.cassandra.io.util.DataOutputBuffer;
+import org.apache.cassandra.locator.InetAddressAndPort;
+import org.apache.cassandra.locator.TokenMetadata;
+import org.apache.cassandra.net.MessagingService;
+import org.apache.cassandra.schema.MigrationManager;
+import org.apache.cassandra.service.PendingRangeCalculatorService;
+import org.apache.cassandra.service.StorageService;
+import org.apache.cassandra.utils.FBUtilities;
+
+import static org.apache.cassandra.distributed.impl.DistributedTestSnitch.toCassandraInetAddressAndPort;
+
+
+public class GossipHelper
+{
+
+ public static ClusterAction clusterAction(InstanceAction action)
+ {
+ return cluster -> cluster.stream().forEach(instance -> {
+ action.apply(cluster, instance);
+ });
+ }
+
+ public static ClusterAction clusterAction(InstanceAction action, Predicate<IInvokableInstance> filter)
+ {
+ return cluster -> cluster.stream().forEach(instance -> {
+ if (filter.test(instance))
+ action.apply(cluster, instance);
+ });
+ }
+
+ public static ClusterAction clusterAction(InstanceAction action, int... instanceIds)
+ {
+ return cluster -> {
+ for (int idx : instanceIds)
+ action.apply(cluster, cluster.get(idx));
+ };
+
+ }
+
+ public static InstanceAction statusToBootstrap(IInvokableInstance newNode)
+ {
+ return new StatusToBootstrap(newNode);
+ }
+
+ public static ClusterAction statusToNormal()
+ {
+ return new ClusterAction()
+ {
+ public void apply(ICluster<IInvokableInstance> cluster)
+ {
+ cluster.stream().forEach((peer) -> {
+ clusterAction(statusToNormal(peer)).apply(cluster);
+ });
+ }
+ };
+ }
+
+ public static InstanceAction statusToNormal(IInvokableInstance newNode)
+ {
+ return new StatusToBootstrap(newNode);
+ }
+
+ public static InstanceAction statusToLeaving(IInvokableInstance newNode)
+ {
+ return new StatusToLeaving(newNode);
+ }
+
+ public static InstanceAction bootstrap()
+ {
+ return new BootstrapAction();
+ }
+
+ public static InstanceAction bootstrap(boolean joinRing, Duration waitForBootstrap, Duration waitForSchema)
+ {
+ return new BootstrapAction(joinRing, waitForBootstrap, waitForSchema);
+ }
+
+ public static InstanceAction disseminateGossipState(IInvokableInstance newNode)
+ {
+ return new DisseminateGossipState(newNode);
+ }
+
+ public static InstanceAction pullSchemaFrom(IInvokableInstance pullFrom)
+ {
+ return new PullSchemaFrom(pullFrom);
+ }
+
+ private static class StatusToBootstrap implements InstanceAction
+ {
+ final IInvokableInstance newNode;
+
+ public StatusToBootstrap(IInvokableInstance newNode)
+ {
+ this.newNode = newNode;
+ }
+
+ public void apply(ICluster<IInvokableInstance> cluster, IInvokableInstance instance)
+ {
+ changeGossipState(instance,
+ newNode,
+ Arrays.asList(tokens(newNode),
+ statusBootstrapping(newNode),
+ statusWithPortBootstrapping(newNode)));
+ }
+ }
+
+ private static class StatusToLeaving implements InstanceAction
+ {
+ final IInvokableInstance newNode;
+
+ public StatusToLeaving(IInvokableInstance newNode)
+ {
+ this.newNode = newNode;
+ }
+
+ public void apply(ICluster<IInvokableInstance> cluster, IInvokableInstance instance)
+ {
+ changeGossipState(instance,
+ newNode,
+ Arrays.asList(tokens(newNode),
+ statusLeaving(newNode),
+ statusWithPortLeaving(newNode)));
+ }
+ }
+
+ private static InstanceAction disableBinary = (cluster, instance) -> {
+ instance.runOnInstance(() -> {
+ StorageService.instance.stopNativeTransport();
+ });
+ };
+
+ public static InstanceAction disableBinary()
+ {
+ return disableBinary;
+ }
+
+ private static class DisseminateGossipState implements InstanceAction
+ {
+ final IInvokableInstance[] from;
+
+ public DisseminateGossipState(IInvokableInstance... from)
+ {
+ this.from = from;
+ }
+
+ public void apply(ICluster<IInvokableInstance> cluster, IInvokableInstance instance)
+ {
+ Map<InetSocketAddress, byte[]> m = new HashMap<>();
+ for (IInvokableInstance node : from)
+ {
+ byte[] epBytes = node.callsOnInstance(() -> {
+ EndpointState epState = Gossiper.instance.getEndpointStateForEndpoint(FBUtilities.getBroadcastAddressAndPort());
+ return toBytes(epState);
+ }).call();
+ m.put(node.broadcastAddress(), epBytes);
+ }
+
+ instance.appliesOnInstance((IIsolatedExecutor.SerializableFunction<Map<InetSocketAddress, byte[]>, Void>)
+ (map) -> {
+ Map<InetAddressAndPort, EndpointState> newState = new HashMap<>();
+ for (Map.Entry<InetSocketAddress, byte[]> e : map.entrySet())
+ newState.put(toCassandraInetAddressAndPort(e.getKey()), fromBytes(e.getValue()));
+
+ Gossiper.runInGossipStageBlocking(() -> {
+ Gossiper.instance.applyStateLocally(newState);
+ });
+ return null;
+ }).apply(m);
+ }
+ }
+
+ public static byte[] toBytes(EndpointState epState)
+ {
+ try (DataOutputBuffer out = new DataOutputBuffer(1024))
+ {
+ EndpointState.serializer.serialize(epState, out, MessagingService.current_version);
+ return out.toByteArray();
+ }
+ catch (IOException e)
+ {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public static EndpointState fromBytes(byte[] bytes)
+ {
+ try (DataInputBuffer in = new DataInputBuffer(bytes))
+ {
+ return EndpointState.serializer.deserialize(in, MessagingService.current_version);
+ }
+ catch (Throwable t)
+ {
+ throw new RuntimeException(t);
+ }
+ }
+
+ private static class PullSchemaFrom implements InstanceAction
+ {
+ final IInvokableInstance pullFrom;
+
+ public PullSchemaFrom(IInvokableInstance pullFrom)
+ {
+ this.pullFrom = pullFrom;
+ }
+
+ public void apply(ICluster<IInvokableInstance> cluster, IInvokableInstance pullTo)
+ {
+ InetSocketAddress addr = pullFrom.broadcastAddress();
+
+ pullTo.runOnInstance(() -> {
+ InetAddressAndPort endpoint = toCassandraInetAddressAndPort(addr);
+ EndpointState state = Gossiper.instance.getEndpointStateForEndpoint(endpoint);
+ MigrationManager.scheduleSchemaPull(endpoint, state);
+ MigrationManager.waitUntilReadyForBootstrap();
+ });
+ }
+ }
+
+ public static class BootstrapAction implements InstanceAction
Review comment:
same as above, why not just have a function? The interface doesn't offer anything and forces the cluster param; which is ignored
##########
File path: test/distributed/org/apache/cassandra/distributed/action/GossipHelper.java
##########
@@ -0,0 +1,464 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.distributed.action;
+
+
+import java.io.IOException;
+import java.net.InetSocketAddress;
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.TimeUnit;
+import java.util.function.Predicate;
+import java.util.stream.Stream;
+
+import net.openhft.chronicle.core.util.SerializableBiFunction;
+import net.openhft.chronicle.core.util.SerializableConsumer;
+import org.apache.cassandra.db.SystemKeyspace;
+import org.apache.cassandra.dht.IPartitioner;
+import org.apache.cassandra.dht.Token;
+import org.apache.cassandra.distributed.api.ICluster;
+import org.apache.cassandra.distributed.api.IInstance;
+import org.apache.cassandra.distributed.api.IInvokableInstance;
+import org.apache.cassandra.distributed.api.IIsolatedExecutor;
+import org.apache.cassandra.distributed.impl.Instance;
+import org.apache.cassandra.distributed.shared.VersionedApplicationState;
+import org.apache.cassandra.gms.ApplicationState;
+import org.apache.cassandra.gms.EndpointState;
+import org.apache.cassandra.gms.Gossiper;
+import org.apache.cassandra.gms.VersionedValue;
+import org.apache.cassandra.io.util.DataInputBuffer;
+import org.apache.cassandra.io.util.DataOutputBuffer;
+import org.apache.cassandra.locator.InetAddressAndPort;
+import org.apache.cassandra.locator.TokenMetadata;
+import org.apache.cassandra.net.MessagingService;
+import org.apache.cassandra.schema.MigrationManager;
+import org.apache.cassandra.service.PendingRangeCalculatorService;
+import org.apache.cassandra.service.StorageService;
+import org.apache.cassandra.utils.FBUtilities;
+
+import static org.apache.cassandra.distributed.impl.DistributedTestSnitch.toCassandraInetAddressAndPort;
+
+
+public class GossipHelper
+{
+
+ public static ClusterAction clusterAction(InstanceAction action)
+ {
+ return cluster -> cluster.stream().forEach(instance -> {
+ action.apply(cluster, instance);
+ });
+ }
+
+ public static ClusterAction clusterAction(InstanceAction action, Predicate<IInvokableInstance> filter)
+ {
+ return cluster -> cluster.stream().forEach(instance -> {
+ if (filter.test(instance))
+ action.apply(cluster, instance);
+ });
+ }
+
+ public static ClusterAction clusterAction(InstanceAction action, int... instanceIds)
+ {
+ return cluster -> {
+ for (int idx : instanceIds)
+ action.apply(cluster, cluster.get(idx));
+ };
+
+ }
+
+ public static InstanceAction statusToBootstrap(IInvokableInstance newNode)
+ {
+ return new StatusToBootstrap(newNode);
+ }
+
+ public static ClusterAction statusToNormal()
+ {
+ return new ClusterAction()
+ {
+ public void apply(ICluster<IInvokableInstance> cluster)
+ {
+ cluster.stream().forEach((peer) -> {
+ clusterAction(statusToNormal(peer)).apply(cluster);
+ });
+ }
+ };
+ }
+
+ public static InstanceAction statusToNormal(IInvokableInstance newNode)
+ {
+ return new StatusToBootstrap(newNode);
+ }
+
+ public static InstanceAction statusToLeaving(IInvokableInstance newNode)
+ {
+ return new StatusToLeaving(newNode);
+ }
+
+ public static InstanceAction bootstrap()
+ {
+ return new BootstrapAction();
+ }
+
+ public static InstanceAction bootstrap(boolean joinRing, Duration waitForBootstrap, Duration waitForSchema)
+ {
+ return new BootstrapAction(joinRing, waitForBootstrap, waitForSchema);
+ }
+
+ public static InstanceAction disseminateGossipState(IInvokableInstance newNode)
+ {
+ return new DisseminateGossipState(newNode);
+ }
+
+ public static InstanceAction pullSchemaFrom(IInvokableInstance pullFrom)
+ {
+ return new PullSchemaFrom(pullFrom);
+ }
+
+ private static class StatusToBootstrap implements InstanceAction
+ {
+ final IInvokableInstance newNode;
+
+ public StatusToBootstrap(IInvokableInstance newNode)
+ {
+ this.newNode = newNode;
+ }
+
+ public void apply(ICluster<IInvokableInstance> cluster, IInvokableInstance instance)
+ {
+ changeGossipState(instance,
+ newNode,
+ Arrays.asList(tokens(newNode),
+ statusBootstrapping(newNode),
+ statusWithPortBootstrapping(newNode)));
+ }
+ }
+
+ private static class StatusToLeaving implements InstanceAction
+ {
+ final IInvokableInstance newNode;
+
+ public StatusToLeaving(IInvokableInstance newNode)
+ {
+ this.newNode = newNode;
+ }
+
+ public void apply(ICluster<IInvokableInstance> cluster, IInvokableInstance instance)
+ {
+ changeGossipState(instance,
+ newNode,
+ Arrays.asList(tokens(newNode),
+ statusLeaving(newNode),
+ statusWithPortLeaving(newNode)));
+ }
+ }
+
+ private static InstanceAction disableBinary = (cluster, instance) -> {
+ instance.runOnInstance(() -> {
+ StorageService.instance.stopNativeTransport();
+ });
+ };
+
+ public static InstanceAction disableBinary()
+ {
+ return disableBinary;
+ }
+
+ private static class DisseminateGossipState implements InstanceAction
+ {
+ final IInvokableInstance[] from;
+
+ public DisseminateGossipState(IInvokableInstance... from)
+ {
+ this.from = from;
+ }
+
+ public void apply(ICluster<IInvokableInstance> cluster, IInvokableInstance instance)
+ {
+ Map<InetSocketAddress, byte[]> m = new HashMap<>();
+ for (IInvokableInstance node : from)
+ {
+ byte[] epBytes = node.callsOnInstance(() -> {
+ EndpointState epState = Gossiper.instance.getEndpointStateForEndpoint(FBUtilities.getBroadcastAddressAndPort());
+ return toBytes(epState);
+ }).call();
+ m.put(node.broadcastAddress(), epBytes);
+ }
+
+ instance.appliesOnInstance((IIsolatedExecutor.SerializableFunction<Map<InetSocketAddress, byte[]>, Void>)
+ (map) -> {
+ Map<InetAddressAndPort, EndpointState> newState = new HashMap<>();
+ for (Map.Entry<InetSocketAddress, byte[]> e : map.entrySet())
+ newState.put(toCassandraInetAddressAndPort(e.getKey()), fromBytes(e.getValue()));
+
+ Gossiper.runInGossipStageBlocking(() -> {
+ Gossiper.instance.applyStateLocally(newState);
+ });
+ return null;
+ }).apply(m);
+ }
+ }
+
+ public static byte[] toBytes(EndpointState epState)
+ {
+ try (DataOutputBuffer out = new DataOutputBuffer(1024))
+ {
+ EndpointState.serializer.serialize(epState, out, MessagingService.current_version);
+ return out.toByteArray();
+ }
+ catch (IOException e)
+ {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public static EndpointState fromBytes(byte[] bytes)
+ {
+ try (DataInputBuffer in = new DataInputBuffer(bytes))
+ {
+ return EndpointState.serializer.deserialize(in, MessagingService.current_version);
+ }
+ catch (Throwable t)
+ {
+ throw new RuntimeException(t);
+ }
+ }
+
+ private static class PullSchemaFrom implements InstanceAction
+ {
+ final IInvokableInstance pullFrom;
+
+ public PullSchemaFrom(IInvokableInstance pullFrom)
+ {
+ this.pullFrom = pullFrom;
+ }
+
+ public void apply(ICluster<IInvokableInstance> cluster, IInvokableInstance pullTo)
Review comment:
why not just have a function? I don't see what the `InstanceAction` interface is providing.
```
GossipHelper.pullSchemaFrom(cluster.get(1), newInstance);
// of if you static import
pullSchemaFrom(cluster.get(1), newInstance);
```
vs
```
new PullSchemaFrom(cluster.get(1)).apply(cluster, newInstance);
```
##########
File path: test/distributed/org/apache/cassandra/distributed/test/BootstrapTest.java
##########
@@ -18,81 +18,254 @@
package org.apache.cassandra.distributed.test;
+import java.net.InetSocketAddress;
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.locks.LockSupport;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.junit.Assert;
import org.junit.Test;
+import com.datastax.driver.core.ResultSet;
+import com.datastax.driver.core.Session;
+import com.datastax.driver.core.SimpleStatement;
+import com.datastax.driver.core.Statement;
+import com.datastax.driver.core.policies.RoundRobinPolicy;
+import org.apache.cassandra.dht.IPartitioner;
+import org.apache.cassandra.dht.Range;
+import org.apache.cassandra.dht.Token;
import org.apache.cassandra.distributed.Cluster;
+import org.apache.cassandra.distributed.action.GossipHelper;
+import org.apache.cassandra.distributed.action.InstanceAction;
import org.apache.cassandra.distributed.api.ConsistencyLevel;
import org.apache.cassandra.distributed.api.ICluster;
+import org.apache.cassandra.distributed.api.IInstance;
import org.apache.cassandra.distributed.api.IInstanceConfig;
+import org.apache.cassandra.distributed.api.IInvokableInstance;
+import org.apache.cassandra.distributed.api.IMessage;
+import org.apache.cassandra.distributed.api.IMessageFilters;
import org.apache.cassandra.distributed.api.TokenSupplier;
+import org.apache.cassandra.distributed.impl.DistributedTestSnitch;
+import org.apache.cassandra.distributed.impl.RowUtil;
import org.apache.cassandra.distributed.shared.NetworkTopology;
+import org.apache.cassandra.locator.EndpointsForRange;
+import org.apache.cassandra.locator.InetAddressAndPort;
+import org.apache.cassandra.net.MessagingService;
+import org.apache.cassandra.service.StorageService;
+import org.apache.cassandra.utils.AssertUtil;
+import org.apache.cassandra.utils.FBUtilities;
+import static org.apache.cassandra.distributed.action.GossipHelper.*;
import static org.apache.cassandra.distributed.api.Feature.GOSSIP;
+import static org.apache.cassandra.distributed.api.Feature.NATIVE_PROTOCOL;
import static org.apache.cassandra.distributed.api.Feature.NETWORK;
+import static org.apache.cassandra.distributed.shared.AssertUtils.assertRows;
+import static org.apache.cassandra.distributed.shared.AssertUtils.row;
-// TODO: this test should be removed after running in-jvm dtests is set up via the shared API repository
public class BootstrapTest extends TestBaseImpl
{
-
@Test
public void bootstrapTest() throws Throwable
{
int originalNodeCount = 2;
int expandedNodeCount = originalNodeCount + 1;
- Cluster.Builder builder = builder().withNodes(originalNodeCount)
- .withTokenSupplier(TokenSupplier.evenlyDistributedTokens(expandedNodeCount))
- .withNodeIdTopology(NetworkTopology.singleDcNetworkTopology(expandedNodeCount, "dc0", "rack0"))
- .withConfig(config -> config.with(NETWORK, GOSSIP));
-
- Map<Integer, Long> withBootstrap = null;
- Map<Integer, Long> naturally = null;
- try (Cluster cluster = builder.withNodes(originalNodeCount).start())
+
+ try (Cluster cluster = builder().withNodes(originalNodeCount)
+ .withTokenSupplier(TokenSupplier.evenlyDistributedTokens(expandedNodeCount))
+ .withNodeIdTopology(NetworkTopology.singleDcNetworkTopology(expandedNodeCount, "dc0", "rack0"))
+ .withConfig(config -> config.with(NETWORK, GOSSIP))
+ .start())
{
- populate(cluster);
+ populate(cluster,0, 100);
IInstanceConfig config = cluster.newInstanceConfig();
- config.set("auto_bootstrap", true);
+ IInvokableInstance newInstance = cluster.initialize(config);
+ newInstance.startup(cluster, IInstance.StartupOption.SKIP_RING_JOIN);
+ clusterAction(statusToBootstrap(newInstance)).apply(cluster);
+ pullSchemaFrom(cluster.get(1)).apply(cluster, newInstance);
+ GossipHelper.bootstrap().apply(cluster, newInstance);
- cluster.bootstrap(config).startup();
+ for (Map.Entry<Integer, Long> e : count(cluster).entrySet())
+ Assert.assertEquals(e.getValue().longValue(), 100L);
+ }
+ }
- cluster.stream().forEach(instance -> {
- instance.nodetool("cleanup", KEYSPACE, "tbl");
- });
+ @Test
+ public void testPendingWrites() throws Throwable
+ {
+ int originalNodeCount = 2;
+ int expandedNodeCount = originalNodeCount + 1;
- withBootstrap = count(cluster);
+ try (Cluster cluster = builder().withNodes(originalNodeCount)
+ .withTokenSupplier(TokenSupplier.evenlyDistributedTokens(expandedNodeCount))
+ .withNodeIdTopology(NetworkTopology.singleDcNetworkTopology(expandedNodeCount, "dc0", "rack0"))
+ .withConfig(config -> config.with(NETWORK, GOSSIP))
+ .start())
+ {
+ populate(cluster, 0, 100);
+
+ IInstanceConfig config = cluster.newInstanceConfig();
+ IInvokableInstance newInstance = cluster.initialize(config);
+ newInstance.startup(cluster, IInstance.StartupOption.SKIP_RING_JOIN);
+ clusterAction(statusToBootstrap(newInstance)).apply(cluster);
+
+ bootstrap(false, Duration.ofSeconds(60), Duration.ofSeconds(10)).apply(cluster, newInstance);
+
+ cluster.get(1).acceptsOnInstance((InetSocketAddress ip) -> {
+ Set<InetAddressAndPort> set = new HashSet<>();
+ for (Map.Entry<Range<Token>, EndpointsForRange.Builder> e : StorageService.instance.getTokenMetadata().getPendingRanges(KEYSPACE))
+ {
+ set.addAll(e.getValue().build().endpoints());
+ }
+ Assert.assertEquals(set.size(), 1);
+ Assert.assertTrue(String.format("%s should contain %s", set, ip),
+ set.contains(DistributedTestSnitch.toCassandraInetAddressAndPort(ip)));
+ }).accept(cluster.get(3).broadcastAddress());
+
+ populate(cluster, 100, 150);
+
+ joinRing().apply(cluster, newInstance);
+ clusterAction(disseminateGossipState(newInstance),1, 2).apply(cluster);
+
+ cluster.get(1).acceptsOnInstance((InetSocketAddress ip) -> {
+ Set<InetAddressAndPort> set = new HashSet<>();
+ for (Map.Entry<Range<Token>, EndpointsForRange.Builder> e : StorageService.instance.getTokenMetadata().getPendingRanges(KEYSPACE))
+ set.addAll(e.getValue().build().endpoints());
+ assert set.size() == 0 : set;
+ }).accept(cluster.get(3).broadcastAddress());
+
+ for (Map.Entry<Integer, Long> e : count(cluster).entrySet())
+ Assert.assertEquals(e.getValue().longValue(), 150L);
}
+ }
- builder = builder.withNodes(expandedNodeCount)
- .withTokenSupplier(TokenSupplier.evenlyDistributedTokens(expandedNodeCount))
- .withConfig(config -> config.with(NETWORK, GOSSIP));
+ @Test
+ public void internodeConnectionsDuringDecom() throws Throwable
+ {
+ ExecutorService executor = Executors.newFixedThreadPool(1);
+ try (Cluster cluster = builder().withNodes(4)
+ .withConfig(config -> config.with(NETWORK, GOSSIP, NATIVE_PROTOCOL))
+ .start())
+ {
+ populate(cluster, 0, 100);
- try (ICluster cluster = builder.start())
+ new DecomissionAction().apply(cluster, cluster.get(1));
+
+ cluster.filters().allVerbs().from(1).messagesMatching((i, i1, iMessage) -> {
+ throw new AssertionError("Decomissioned node should not send any messages");
+ }).drop();
+
+
+ Map<Integer, Long> connectionAttempts = new HashMap<>();
+ long deadline = System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(10);
+
+ // Wait 10 seconds and check if there are any new connection attempts to the decomissioned node
+ while (System.currentTimeMillis() <= deadline)
+ {
+ for (int i = 2; i <= cluster.size(); i++)
+ {
+ Object[][] res = cluster.get(i).executeInternal("SELECT active_connections, connection_attempts FROM system_views.internode_outbound WHERE address = '127.0.0.1' AND port = 7012");
+ Assert.assertEquals(1, res.length);
+ Assert.assertEquals(0L, ((Long) res[0][0]).longValue());
+ long attempts = ((Long) res[0][1]).longValue();
+ if (connectionAttempts.get(i) == null)
+ connectionAttempts.put(i, attempts);
+ else
+ Assert.assertEquals(connectionAttempts.get(i), (Long) attempts);
+ }
+ LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(100));
+ }
+ }
+ }
+
+ @Test
+ public void clientConnectionsDuringDecom() throws Throwable
+ {
+ ExecutorService executor = Executors.newFixedThreadPool(1);
+ try (Cluster cluster = builder().withNodes(4)
+ .withConfig(config -> config.with(NETWORK, GOSSIP, NATIVE_PROTOCOL))
+ .start())
{
- populate(cluster);
- naturally = count(cluster);
+ populate(cluster, 0, 100);
+
+ try (com.datastax.driver.core.Cluster client = com.datastax.driver.core.Cluster.builder().addContactPoint("127.0.0.1")
+ .withLoadBalancingPolicy(new RoundRobinPolicy())
+ .build();
+ Session session = client.connect())
+ {
+ CompletableFuture.runAsync(() -> {
+ while (!Thread.currentThread().isInterrupted())
+ {
+ if (client.getMetadata().getAllHosts().size() == cluster.size())
+ return;
+ LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(100));
+ }
+ }, executor).get(1, TimeUnit.MINUTES);
+
+ new DecomissionAction().apply(cluster, cluster.get(1));
+
+ Assert.assertEquals(cluster.size() - 1, client.getMetadata().getAllHosts().size());
+ for (int i = 0; i < 100; i++)
+ {
+ Statement select = new SimpleStatement("select * from " + KEYSPACE + ".tbl WHERE pk = " + i).setConsistencyLevel(com.datastax.driver.core.ConsistencyLevel.ALL);
+ final ResultSet resultSet = session.execute(select);
+ assertRows(RowUtil.toObjects(resultSet), row(i, i, i));
+ }
+ Assert.assertEquals(cluster.size() - 1, client.getMetadata().getAllHosts().size());
+ }
}
+ }
- for (Map.Entry<Integer, Long> e : withBootstrap.entrySet())
- Assert.assertTrue(e.getValue() >= naturally.get(e.getKey()));
+ public static InstanceAction joinRing()
+ {
+ return new JoinRing();
}
- public void populate(ICluster cluster)
+ private static class JoinRing implements InstanceAction
{
- cluster.schemaChange("CREATE KEYSPACE " + KEYSPACE + " WITH replication = {'class': 'SimpleStrategy', 'replication_factor': " + 3 + "};");
- cluster.schemaChange("CREATE TABLE " + KEYSPACE + ".tbl (pk int, ck int, v int, PRIMARY KEY (pk, ck))");
+ public void apply(ICluster<IInvokableInstance> cluster, IInvokableInstance instance)
Review comment:
this looks like the unsafe version of `nodetool join`, is there a reason to avoid bootstrap?
Also, not sure what the difference is to the below, it looks mostly the same
```
System.setProperty("cassandra.auto_bootstrap", "false");
instance.nodetoolResults("join").asserts().success();
```
##########
File path: test/distributed/org/apache/cassandra/distributed/action/GossipHelper.java
##########
@@ -0,0 +1,464 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.distributed.action;
+
+
+import java.io.IOException;
+import java.net.InetSocketAddress;
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.TimeUnit;
+import java.util.function.Predicate;
+import java.util.stream.Stream;
+
+import net.openhft.chronicle.core.util.SerializableBiFunction;
+import net.openhft.chronicle.core.util.SerializableConsumer;
+import org.apache.cassandra.db.SystemKeyspace;
+import org.apache.cassandra.dht.IPartitioner;
+import org.apache.cassandra.dht.Token;
+import org.apache.cassandra.distributed.api.ICluster;
+import org.apache.cassandra.distributed.api.IInstance;
+import org.apache.cassandra.distributed.api.IInvokableInstance;
+import org.apache.cassandra.distributed.api.IIsolatedExecutor;
+import org.apache.cassandra.distributed.impl.Instance;
+import org.apache.cassandra.distributed.shared.VersionedApplicationState;
+import org.apache.cassandra.gms.ApplicationState;
+import org.apache.cassandra.gms.EndpointState;
+import org.apache.cassandra.gms.Gossiper;
+import org.apache.cassandra.gms.VersionedValue;
+import org.apache.cassandra.io.util.DataInputBuffer;
+import org.apache.cassandra.io.util.DataOutputBuffer;
+import org.apache.cassandra.locator.InetAddressAndPort;
+import org.apache.cassandra.locator.TokenMetadata;
+import org.apache.cassandra.net.MessagingService;
+import org.apache.cassandra.schema.MigrationManager;
+import org.apache.cassandra.service.PendingRangeCalculatorService;
+import org.apache.cassandra.service.StorageService;
+import org.apache.cassandra.utils.FBUtilities;
+
+import static org.apache.cassandra.distributed.impl.DistributedTestSnitch.toCassandraInetAddressAndPort;
+
+
+public class GossipHelper
+{
+
+ public static ClusterAction clusterAction(InstanceAction action)
Review comment:
ClusterAction seems to be a abstraction over looping, so feel the code is more clear by just looping
examples:
```
clusterAction(statusToBootstrap(newInstance)).apply(cluster);
// vs
cluster.forEach(i -> statusToBootstrap(i, newInstance));
```
or use a specific set of nodes
```
clusterAction(disseminateGossipState(newInstance), 1, 2).apply(cluster);
// vs
IntStream.of(1, 2).forEach(i -> disseminateGossipState(i, newInstance));
```
In these examples, it is more clear to see the loop than the ClusterAction abstraction.
##########
File path: test/distributed/org/apache/cassandra/distributed/action/GossipHelper.java
##########
@@ -0,0 +1,464 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.distributed.action;
+
+
+import java.io.IOException;
+import java.net.InetSocketAddress;
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.TimeUnit;
+import java.util.function.Predicate;
+import java.util.stream.Stream;
+
+import net.openhft.chronicle.core.util.SerializableBiFunction;
+import net.openhft.chronicle.core.util.SerializableConsumer;
+import org.apache.cassandra.db.SystemKeyspace;
+import org.apache.cassandra.dht.IPartitioner;
+import org.apache.cassandra.dht.Token;
+import org.apache.cassandra.distributed.api.ICluster;
+import org.apache.cassandra.distributed.api.IInstance;
+import org.apache.cassandra.distributed.api.IInvokableInstance;
+import org.apache.cassandra.distributed.api.IIsolatedExecutor;
+import org.apache.cassandra.distributed.impl.Instance;
+import org.apache.cassandra.distributed.shared.VersionedApplicationState;
+import org.apache.cassandra.gms.ApplicationState;
+import org.apache.cassandra.gms.EndpointState;
+import org.apache.cassandra.gms.Gossiper;
+import org.apache.cassandra.gms.VersionedValue;
+import org.apache.cassandra.io.util.DataInputBuffer;
+import org.apache.cassandra.io.util.DataOutputBuffer;
+import org.apache.cassandra.locator.InetAddressAndPort;
+import org.apache.cassandra.locator.TokenMetadata;
+import org.apache.cassandra.net.MessagingService;
+import org.apache.cassandra.schema.MigrationManager;
+import org.apache.cassandra.service.PendingRangeCalculatorService;
+import org.apache.cassandra.service.StorageService;
+import org.apache.cassandra.utils.FBUtilities;
+
+import static org.apache.cassandra.distributed.impl.DistributedTestSnitch.toCassandraInetAddressAndPort;
+
+
+public class GossipHelper
Review comment:
my comments feedback for this class is the `InstanceAction` interface, it would be simpler to just have a function.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
[GitHub] [cassandra] ifesdjeen commented on a change in pull request #759: Improve machinery for testing bootstrap and range movements
Posted by GitBox <gi...@apache.org>.
ifesdjeen commented on a change in pull request #759:
URL: https://github.com/apache/cassandra/pull/759#discussion_r504567615
##########
File path: src/java/org/apache/cassandra/net/MessagingService.java
##########
@@ -431,6 +431,12 @@ public void shutdown()
public void shutdown(long timeout, TimeUnit units, boolean shutdownGracefully, boolean shutdownExecutors)
{
+ if (isShuttingDown)
Review comment:
This is because we're doing decommission on the node. You'd hit a "stage is shutdown" exception on "real" node shutdown otherwise.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
[GitHub] [cassandra] ifesdjeen commented on a change in pull request #759: Improve machinery for testing bootstrap and range movements
Posted by GitBox <gi...@apache.org>.
ifesdjeen commented on a change in pull request #759:
URL: https://github.com/apache/cassandra/pull/759#discussion_r508267418
##########
File path: test/distributed/org/apache/cassandra/distributed/action/GossipHelper.java
##########
@@ -0,0 +1,431 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.distributed.action;
+
+import java.io.IOException;
+import java.io.Serializable;
+import java.net.InetSocketAddress;
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.TimeUnit;
+import java.util.stream.Stream;
+
+import net.openhft.chronicle.core.util.SerializableBiFunction;
+import org.apache.cassandra.db.SystemKeyspace;
+import org.apache.cassandra.dht.IPartitioner;
+import org.apache.cassandra.dht.Token;
+import org.apache.cassandra.distributed.api.IInstance;
+import org.apache.cassandra.distributed.api.IInvokableInstance;
+import org.apache.cassandra.distributed.api.IIsolatedExecutor;
+import org.apache.cassandra.distributed.impl.Instance;
+import org.apache.cassandra.distributed.shared.VersionedApplicationState;
+import org.apache.cassandra.gms.ApplicationState;
+import org.apache.cassandra.gms.EndpointState;
+import org.apache.cassandra.gms.Gossiper;
+import org.apache.cassandra.gms.VersionedValue;
+import org.apache.cassandra.io.util.DataInputBuffer;
+import org.apache.cassandra.io.util.DataOutputBuffer;
+import org.apache.cassandra.locator.InetAddressAndPort;
+import org.apache.cassandra.locator.TokenMetadata;
+import org.apache.cassandra.net.MessagingService;
+import org.apache.cassandra.schema.MigrationManager;
+import org.apache.cassandra.service.PendingRangeCalculatorService;
+import org.apache.cassandra.service.StorageService;
+import org.apache.cassandra.utils.FBUtilities;
+
+import static org.apache.cassandra.distributed.impl.DistributedTestSnitch.toCassandraInetAddressAndPort;
+
+public class GossipHelper
+{
+ public static InstanceAction statusToBootstrap(IInvokableInstance newNode)
+ {
+ return (instance) ->
+ {
+ changeGossipState(instance,
+ newNode,
+ Arrays.asList(tokens(newNode),
+ statusBootstrapping(newNode),
+ statusWithPortBootstrapping(newNode)));
+ };
+ }
+
+ public static InstanceAction statusToNormal(IInvokableInstance peer)
+ {
+ return (target) ->
+ {
+ changeGossipState(target,
+ peer,
+ Arrays.asList(tokens(peer),
+ statusNormal(peer),
+ releaseVersion(peer),
+ statusWithPortNormal(peer)));
+ };
+ }
+
+ /**
+ * This method is unsafe and should be used _only_ when gossip is not used or available: it creates versioned values on the
+ * target instance, which means Gossip versioning gets out of sync. Use a safe couterpart at all times when performing _any_
+ * ring movement operations _or_ if Gossip is used.
+ */
+ public static InstanceAction unsafeStatusToNormal(IInstance peer)
+ {
+ return (target) ->
+ {
+ changeGossipState(target,
+ peer,
+ Arrays.asList(unsafeVersionedToken(target,
+ ApplicationState.TOKENS,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).tokens(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeVersionedToken(target,
+ ApplicationState.STATUS,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeVersionedToken(target,
+ ApplicationState.STATUS_WITH_PORT,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeReleaseVersion(target,
+ peer.config().getString("partitioner"),
+ peer.getReleaseVersionString())));
+ };
+ }
+
+ public static InstanceAction statusToLeaving(IInvokableInstance newNode)
+ {
+ return (instance) -> {
+ changeGossipState(instance,
+ newNode,
+ Arrays.asList(tokens(newNode),
+ statusLeaving(newNode),
+ statusWithPortLeaving(newNode)));
+ };
+ }
+
+ public static InstanceAction bootstrap()
+ {
+ return new BootstrapAction();
+ }
+
+ public static InstanceAction bootstrap(boolean joinRing, Duration waitForBootstrap, Duration waitForSchema)
+ {
+ return new BootstrapAction(joinRing, waitForBootstrap, waitForSchema);
+ }
+
+ public static InstanceAction disseminateGossipState(IInvokableInstance newNode)
+ {
+ return new DisseminateGossipState(newNode);
+ }
+
+ public static InstanceAction pullSchemaFrom(IInvokableInstance pullFrom)
+ {
+ return new PullSchemaFrom(pullFrom);
+ }
+
+ private static InstanceAction disableBinary()
+ {
+ return (instance) -> {
+ instance.runOnInstance(StorageService.instance::stopNativeTransport);
+ };
+ }
+
+ private static class DisseminateGossipState implements InstanceAction
+ {
+ final Map<InetSocketAddress, byte[]> gossipState;
+
+ public DisseminateGossipState(IInvokableInstance... from)
+ {
+ gossipState = new HashMap<>();
+ for (IInvokableInstance node : from)
+ {
+ byte[] epBytes = node.callsOnInstance(() -> {
+ EndpointState epState = Gossiper.instance.getEndpointStateForEndpoint(FBUtilities.getBroadcastAddressAndPort());
+ return toBytes(epState);
+ }).call();
+ gossipState.put(node.broadcastAddress(), epBytes);
+ }
+ }
+
+ public void accept(IInvokableInstance instance)
+ {
+ instance.appliesOnInstance((IIsolatedExecutor.SerializableFunction<Map<InetSocketAddress, byte[]>, Void>)
+ (map) -> {
+ Map<InetAddressAndPort, EndpointState> newState = new HashMap<>();
+ for (Map.Entry<InetSocketAddress, byte[]> e : map.entrySet())
+ newState.put(toCassandraInetAddressAndPort(e.getKey()), fromBytes(e.getValue()));
+
+ Gossiper.runInGossipStageBlocking(() -> {
+ Gossiper.instance.applyStateLocally(newState);
+ });
+ return null;
+ }).apply(gossipState);
+ }
+ }
+
+ public static byte[] toBytes(EndpointState epState)
+ {
+ try (DataOutputBuffer out = new DataOutputBuffer(1024))
+ {
+ EndpointState.serializer.serialize(epState, out, MessagingService.current_version);
+ return out.toByteArray();
+ }
+ catch (IOException e)
+ {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public static EndpointState fromBytes(byte[] bytes)
+ {
+ try (DataInputBuffer in = new DataInputBuffer(bytes))
+ {
+ return EndpointState.serializer.deserialize(in, MessagingService.current_version);
+ }
+ catch (Throwable t)
+ {
+ throw new RuntimeException(t);
+ }
+ }
+
+ private static class PullSchemaFrom implements InstanceAction
+ {
+ final InetSocketAddress pullFrom;
+
+ public PullSchemaFrom(IInvokableInstance pullFrom)
+ {
+ this.pullFrom = pullFrom.broadcastAddress();;
+ }
+
+ public void accept(IInvokableInstance pullTo)
+ {
+ pullTo.acceptsOnInstance((InetSocketAddress pullFrom) -> {
+ InetAddressAndPort endpoint = toCassandraInetAddressAndPort(pullFrom);
+ EndpointState state = Gossiper.instance.getEndpointStateForEndpoint(endpoint);
+ MigrationManager.scheduleSchemaPull(endpoint, state);
+ MigrationManager.waitUntilReadyForBootstrap();
+ }).accept(pullFrom);
+ }
+ }
+
+ private static class BootstrapAction implements InstanceAction, Serializable
+ {
+ private final boolean joinRing;
+ private final Duration waitForBootstrap;
+ private final Duration waitForSchema;
+
+ public BootstrapAction()
+ {
+ this(true, Duration.ofMinutes(10), Duration.ofSeconds(10));
+ }
+
+ public BootstrapAction(boolean joinRing, Duration waitForBootstrap, Duration waitForSchema)
+ {
+ this.joinRing = joinRing;
+ this.waitForBootstrap = waitForBootstrap;
+ this.waitForSchema = waitForSchema;
+ }
+
+ public void accept(IInvokableInstance instance)
+ {
+ instance.appliesOnInstance((String partitionerString, String tokenString) -> {
+ IPartitioner partitioner = FBUtilities.newPartitioner(partitionerString);
+ List<Token> tokens = Collections.singletonList(partitioner.getTokenFactory().fromString(tokenString));
+ try
+ {
+ SystemKeyspace.setBootstrapState(SystemKeyspace.BootstrapState.IN_PROGRESS);
+ StorageService.instance.waitForSchema((int) waitForSchema.toMillis());
+ PendingRangeCalculatorService.instance.blockUntilFinished();
+ StorageService.instance.startBootstrap(tokens).get(waitForBootstrap.toMillis(), TimeUnit.MILLISECONDS);
+ StorageService.instance.setUpDistributedSystemKeyspaces();
+ if (joinRing)
+ StorageService.instance.finishJoiningRing(true, tokens);
+ }
+ catch (Throwable t)
+ {
+ throw new RuntimeException(t);
+ }
+
+ return null;
+ }).apply(instance.config().getString("partitioner"), instance.config().getString("initial_token"));
+ }
+ }
+
+ public static InstanceAction decomission()
+ {
+ return (target) -> {
+ target.runOnInstance(() -> {
+ try
+ {
+ StorageService.instance.decommission(false);
+ }
+ catch (InterruptedException e)
+ {
+ throw new RuntimeException();
+ }
+ });
+ };
+ }
+
+
+ public static VersionedApplicationState tokens(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.TOKENS, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).tokens(tokens));
+ }
+
+ public static VersionedApplicationState unsafeReleaseVersion(IInvokableInstance instance, String partitionerStr, String releaseVersionStr)
+ {
+ return instance.appliesOnInstance((String partitionerString, String releaseVersion) -> {
+ IPartitioner partitioner = FBUtilities.newPartitioner(partitionerString);
+ VersionedValue versionedValue = new VersionedValue.VersionedValueFactory(partitioner).releaseVersion(releaseVersion);
+ return new VersionedApplicationState(ApplicationState.RELEASE_VERSION.ordinal(), versionedValue.value, versionedValue.version);
+ }).apply(partitionerStr, releaseVersionStr);
+ }
+
+ public static VersionedApplicationState releaseVersion(IInvokableInstance instance)
+ {
+ return unsafeReleaseVersion(instance, instance.config().getString("partitioner"), instance.getReleaseVersionString());
+ }
+
+ public static VersionedApplicationState statusNormal(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens));
+ }
+
+ public static VersionedApplicationState statusWithPortNormal(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS_WITH_PORT, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens));
+ }
+
+ public static VersionedApplicationState statusBootstrapping(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).bootstrapping(tokens));
+ }
+
+ public static VersionedApplicationState statusWithPortBootstrapping(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS_WITH_PORT, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).bootstrapping(tokens));
+ }
+
+ public static VersionedApplicationState statusLeaving(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).leaving(tokens));
+ }
+
+ public static VersionedApplicationState statusWithPortLeaving(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS_WITH_PORT, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).leaving(tokens));
+ }
+
+ public static VersionedValue toVersionedValue(VersionedApplicationState vv)
+ {
+ return VersionedValue.unsafeMakeVersionedValue(vv.value, vv.version);
+ }
+
+ public static ApplicationState toApplicationState(VersionedApplicationState vv)
+ {
+ return ApplicationState.values()[vv.applicationState];
+ }
+
+ public static VersionedApplicationState unsafeVersionedToken(IInvokableInstance instance,
+ ApplicationState applicationState,
+ SerializableBiFunction<IPartitioner, Collection<Token>, VersionedValue> supplier,
+ String partitionerStr, String initialTokenStr)
+ {
+ return instance.appliesOnInstance((String partitionerString, String tokenString) -> {
+ IPartitioner partitioner = FBUtilities.newPartitioner(partitionerString);
+ Token token = partitioner.getTokenFactory().fromString(tokenString);
+
+ VersionedValue versionedValue = supplier.apply(partitioner, Collections.singleton(token));
+ return new VersionedApplicationState(applicationState.ordinal(), versionedValue.value, versionedValue.version);
+ }).apply(partitionerStr, initialTokenStr);
+ }
+
+ public static VersionedApplicationState versionedToken(IInvokableInstance instance, ApplicationState applicationState, SerializableBiFunction<IPartitioner, Collection<Token>, VersionedValue> supplier)
+ {
+ return unsafeVersionedToken(instance, applicationState, supplier, instance.config().getString("partitioner"), instance.config().getString("initial_token"));
+ }
+
+ public void removeFromRing(IInstance peer)
Review comment:
Thanks for spotting. You're right, this did throw because it wasn't wrapped into `InstanceAction`: I was initially using this for testing forced removal from the ring. I've added `nodeNotInRingTest` for this.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
[GitHub] [cassandra] ifesdjeen commented on a change in pull request #759: Improve machinery for testing bootstrap and range movements
Posted by GitBox <gi...@apache.org>.
ifesdjeen commented on a change in pull request #759:
URL: https://github.com/apache/cassandra/pull/759#discussion_r507830716
##########
File path: test/distributed/org/apache/cassandra/distributed/impl/AbstractCluster.java
##########
@@ -448,6 +444,33 @@ public int size()
i.config().localRack().equals(rackName));
}
+ public void run(Consumer<? super I> action, Predicate<I> filter) {
Review comment:
👍 Fixed for this and other `run` overloads
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
[GitHub] [cassandra] ifesdjeen commented on a change in pull request #759: Improve machinery for testing bootstrap and range movements
Posted by GitBox <gi...@apache.org>.
ifesdjeen commented on a change in pull request #759:
URL: https://github.com/apache/cassandra/pull/759#discussion_r507828982
##########
File path: src/java/org/apache/cassandra/schema/MigrationManager.java
##########
@@ -40,6 +40,7 @@
import org.apache.cassandra.net.MessagingService;
import org.apache.cassandra.schema.Keyspaces.KeyspacesDiff;
import org.apache.cassandra.utils.FBUtilities;
+import org.assertj.core.util.VisibleForTesting;
Review comment:
True; switched to guava one in one of the commits. Thanks for spotting!
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
[GitHub] [cassandra] ifesdjeen commented on a change in pull request #759: Improve machinery for testing bootstrap and range movements
Posted by GitBox <gi...@apache.org>.
ifesdjeen commented on a change in pull request #759:
URL: https://github.com/apache/cassandra/pull/759#discussion_r508213228
##########
File path: test/distributed/org/apache/cassandra/distributed/action/GossipHelper.java
##########
@@ -0,0 +1,431 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.distributed.action;
+
+import java.io.IOException;
+import java.io.Serializable;
+import java.net.InetSocketAddress;
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.TimeUnit;
+import java.util.stream.Stream;
+
+import net.openhft.chronicle.core.util.SerializableBiFunction;
+import org.apache.cassandra.db.SystemKeyspace;
+import org.apache.cassandra.dht.IPartitioner;
+import org.apache.cassandra.dht.Token;
+import org.apache.cassandra.distributed.api.IInstance;
+import org.apache.cassandra.distributed.api.IInvokableInstance;
+import org.apache.cassandra.distributed.api.IIsolatedExecutor;
+import org.apache.cassandra.distributed.impl.Instance;
+import org.apache.cassandra.distributed.shared.VersionedApplicationState;
+import org.apache.cassandra.gms.ApplicationState;
+import org.apache.cassandra.gms.EndpointState;
+import org.apache.cassandra.gms.Gossiper;
+import org.apache.cassandra.gms.VersionedValue;
+import org.apache.cassandra.io.util.DataInputBuffer;
+import org.apache.cassandra.io.util.DataOutputBuffer;
+import org.apache.cassandra.locator.InetAddressAndPort;
+import org.apache.cassandra.locator.TokenMetadata;
+import org.apache.cassandra.net.MessagingService;
+import org.apache.cassandra.schema.MigrationManager;
+import org.apache.cassandra.service.PendingRangeCalculatorService;
+import org.apache.cassandra.service.StorageService;
+import org.apache.cassandra.utils.FBUtilities;
+
+import static org.apache.cassandra.distributed.impl.DistributedTestSnitch.toCassandraInetAddressAndPort;
+
+public class GossipHelper
+{
+ public static InstanceAction statusToBootstrap(IInvokableInstance newNode)
+ {
+ return (instance) ->
+ {
+ changeGossipState(instance,
+ newNode,
+ Arrays.asList(tokens(newNode),
+ statusBootstrapping(newNode),
+ statusWithPortBootstrapping(newNode)));
+ };
+ }
+
+ public static InstanceAction statusToNormal(IInvokableInstance peer)
+ {
+ return (target) ->
+ {
+ changeGossipState(target,
+ peer,
+ Arrays.asList(tokens(peer),
+ statusNormal(peer),
+ releaseVersion(peer),
+ statusWithPortNormal(peer)));
+ };
+ }
+
+ /**
+ * This method is unsafe and should be used _only_ when gossip is not used or available: it creates versioned values on the
+ * target instance, which means Gossip versioning gets out of sync. Use a safe couterpart at all times when performing _any_
+ * ring movement operations _or_ if Gossip is used.
+ */
+ public static InstanceAction unsafeStatusToNormal(IInstance peer)
+ {
+ return (target) ->
+ {
+ changeGossipState(target,
+ peer,
+ Arrays.asList(unsafeVersionedToken(target,
+ ApplicationState.TOKENS,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).tokens(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeVersionedToken(target,
+ ApplicationState.STATUS,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeVersionedToken(target,
+ ApplicationState.STATUS_WITH_PORT,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeReleaseVersion(target,
+ peer.config().getString("partitioner"),
+ peer.getReleaseVersionString())));
+ };
+ }
+
+ public static InstanceAction statusToLeaving(IInvokableInstance newNode)
+ {
+ return (instance) -> {
+ changeGossipState(instance,
+ newNode,
+ Arrays.asList(tokens(newNode),
+ statusLeaving(newNode),
+ statusWithPortLeaving(newNode)));
+ };
+ }
+
+ public static InstanceAction bootstrap()
+ {
+ return new BootstrapAction();
+ }
+
+ public static InstanceAction bootstrap(boolean joinRing, Duration waitForBootstrap, Duration waitForSchema)
+ {
+ return new BootstrapAction(joinRing, waitForBootstrap, waitForSchema);
+ }
+
+ public static InstanceAction disseminateGossipState(IInvokableInstance newNode)
+ {
+ return new DisseminateGossipState(newNode);
+ }
+
+ public static InstanceAction pullSchemaFrom(IInvokableInstance pullFrom)
+ {
+ return new PullSchemaFrom(pullFrom);
+ }
+
+ private static InstanceAction disableBinary()
+ {
+ return (instance) -> {
Review comment:
Sure, that makes sense. Switched to `instance.nodetoolResult("disablebinary").asserts().success();`. Thanks!
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
[GitHub] [cassandra] ifesdjeen commented on a change in pull request #759: Improve machinery for testing bootstrap and range movements
Posted by GitBox <gi...@apache.org>.
ifesdjeen commented on a change in pull request #759:
URL: https://github.com/apache/cassandra/pull/759#discussion_r504034027
##########
File path: test/distributed/org/apache/cassandra/distributed/test/BootstrapTest.java
##########
@@ -18,81 +18,254 @@
package org.apache.cassandra.distributed.test;
+import java.net.InetSocketAddress;
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.locks.LockSupport;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.junit.Assert;
import org.junit.Test;
+import com.datastax.driver.core.ResultSet;
+import com.datastax.driver.core.Session;
+import com.datastax.driver.core.SimpleStatement;
+import com.datastax.driver.core.Statement;
+import com.datastax.driver.core.policies.RoundRobinPolicy;
+import org.apache.cassandra.dht.IPartitioner;
+import org.apache.cassandra.dht.Range;
+import org.apache.cassandra.dht.Token;
import org.apache.cassandra.distributed.Cluster;
+import org.apache.cassandra.distributed.action.GossipHelper;
+import org.apache.cassandra.distributed.action.InstanceAction;
import org.apache.cassandra.distributed.api.ConsistencyLevel;
import org.apache.cassandra.distributed.api.ICluster;
+import org.apache.cassandra.distributed.api.IInstance;
import org.apache.cassandra.distributed.api.IInstanceConfig;
+import org.apache.cassandra.distributed.api.IInvokableInstance;
+import org.apache.cassandra.distributed.api.IMessage;
+import org.apache.cassandra.distributed.api.IMessageFilters;
import org.apache.cassandra.distributed.api.TokenSupplier;
+import org.apache.cassandra.distributed.impl.DistributedTestSnitch;
+import org.apache.cassandra.distributed.impl.RowUtil;
import org.apache.cassandra.distributed.shared.NetworkTopology;
+import org.apache.cassandra.locator.EndpointsForRange;
+import org.apache.cassandra.locator.InetAddressAndPort;
+import org.apache.cassandra.net.MessagingService;
+import org.apache.cassandra.service.StorageService;
+import org.apache.cassandra.utils.AssertUtil;
+import org.apache.cassandra.utils.FBUtilities;
+import static org.apache.cassandra.distributed.action.GossipHelper.*;
import static org.apache.cassandra.distributed.api.Feature.GOSSIP;
+import static org.apache.cassandra.distributed.api.Feature.NATIVE_PROTOCOL;
import static org.apache.cassandra.distributed.api.Feature.NETWORK;
+import static org.apache.cassandra.distributed.shared.AssertUtils.assertRows;
+import static org.apache.cassandra.distributed.shared.AssertUtils.row;
-// TODO: this test should be removed after running in-jvm dtests is set up via the shared API repository
public class BootstrapTest extends TestBaseImpl
{
-
@Test
public void bootstrapTest() throws Throwable
{
int originalNodeCount = 2;
int expandedNodeCount = originalNodeCount + 1;
- Cluster.Builder builder = builder().withNodes(originalNodeCount)
- .withTokenSupplier(TokenSupplier.evenlyDistributedTokens(expandedNodeCount))
- .withNodeIdTopology(NetworkTopology.singleDcNetworkTopology(expandedNodeCount, "dc0", "rack0"))
- .withConfig(config -> config.with(NETWORK, GOSSIP));
-
- Map<Integer, Long> withBootstrap = null;
- Map<Integer, Long> naturally = null;
- try (Cluster cluster = builder.withNodes(originalNodeCount).start())
+
+ try (Cluster cluster = builder().withNodes(originalNodeCount)
+ .withTokenSupplier(TokenSupplier.evenlyDistributedTokens(expandedNodeCount))
+ .withNodeIdTopology(NetworkTopology.singleDcNetworkTopology(expandedNodeCount, "dc0", "rack0"))
+ .withConfig(config -> config.with(NETWORK, GOSSIP))
+ .start())
{
- populate(cluster);
+ populate(cluster,0, 100);
IInstanceConfig config = cluster.newInstanceConfig();
- config.set("auto_bootstrap", true);
+ IInvokableInstance newInstance = cluster.initialize(config);
+ newInstance.startup(cluster, IInstance.StartupOption.SKIP_RING_JOIN);
+ clusterAction(statusToBootstrap(newInstance)).apply(cluster);
+ pullSchemaFrom(cluster.get(1)).apply(cluster, newInstance);
+ GossipHelper.bootstrap().apply(cluster, newInstance);
- cluster.bootstrap(config).startup();
+ for (Map.Entry<Integer, Long> e : count(cluster).entrySet())
+ Assert.assertEquals(e.getValue().longValue(), 100L);
+ }
+ }
- cluster.stream().forEach(instance -> {
- instance.nodetool("cleanup", KEYSPACE, "tbl");
- });
+ @Test
+ public void testPendingWrites() throws Throwable
+ {
+ int originalNodeCount = 2;
+ int expandedNodeCount = originalNodeCount + 1;
- withBootstrap = count(cluster);
+ try (Cluster cluster = builder().withNodes(originalNodeCount)
+ .withTokenSupplier(TokenSupplier.evenlyDistributedTokens(expandedNodeCount))
+ .withNodeIdTopology(NetworkTopology.singleDcNetworkTopology(expandedNodeCount, "dc0", "rack0"))
+ .withConfig(config -> config.with(NETWORK, GOSSIP))
+ .start())
+ {
+ populate(cluster, 0, 100);
+
+ IInstanceConfig config = cluster.newInstanceConfig();
+ IInvokableInstance newInstance = cluster.initialize(config);
+ newInstance.startup(cluster, IInstance.StartupOption.SKIP_RING_JOIN);
+ clusterAction(statusToBootstrap(newInstance)).apply(cluster);
+
+ bootstrap(false, Duration.ofSeconds(60), Duration.ofSeconds(10)).apply(cluster, newInstance);
+
+ cluster.get(1).acceptsOnInstance((InetSocketAddress ip) -> {
+ Set<InetAddressAndPort> set = new HashSet<>();
+ for (Map.Entry<Range<Token>, EndpointsForRange.Builder> e : StorageService.instance.getTokenMetadata().getPendingRanges(KEYSPACE))
+ {
+ set.addAll(e.getValue().build().endpoints());
+ }
+ Assert.assertEquals(set.size(), 1);
+ Assert.assertTrue(String.format("%s should contain %s", set, ip),
+ set.contains(DistributedTestSnitch.toCassandraInetAddressAndPort(ip)));
+ }).accept(cluster.get(3).broadcastAddress());
+
+ populate(cluster, 100, 150);
+
+ joinRing().apply(cluster, newInstance);
+ clusterAction(disseminateGossipState(newInstance),1, 2).apply(cluster);
+
+ cluster.get(1).acceptsOnInstance((InetSocketAddress ip) -> {
+ Set<InetAddressAndPort> set = new HashSet<>();
+ for (Map.Entry<Range<Token>, EndpointsForRange.Builder> e : StorageService.instance.getTokenMetadata().getPendingRanges(KEYSPACE))
+ set.addAll(e.getValue().build().endpoints());
+ assert set.size() == 0 : set;
+ }).accept(cluster.get(3).broadcastAddress());
+
+ for (Map.Entry<Integer, Long> e : count(cluster).entrySet())
+ Assert.assertEquals(e.getValue().longValue(), 150L);
}
+ }
- builder = builder.withNodes(expandedNodeCount)
- .withTokenSupplier(TokenSupplier.evenlyDistributedTokens(expandedNodeCount))
- .withConfig(config -> config.with(NETWORK, GOSSIP));
+ @Test
+ public void internodeConnectionsDuringDecom() throws Throwable
+ {
+ ExecutorService executor = Executors.newFixedThreadPool(1);
+ try (Cluster cluster = builder().withNodes(4)
+ .withConfig(config -> config.with(NETWORK, GOSSIP, NATIVE_PROTOCOL))
+ .start())
+ {
+ populate(cluster, 0, 100);
- try (ICluster cluster = builder.start())
+ new DecomissionAction().apply(cluster, cluster.get(1));
+
+ cluster.filters().allVerbs().from(1).messagesMatching((i, i1, iMessage) -> {
+ throw new AssertionError("Decomissioned node should not send any messages");
+ }).drop();
+
+
+ Map<Integer, Long> connectionAttempts = new HashMap<>();
+ long deadline = System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(10);
+
+ // Wait 10 seconds and check if there are any new connection attempts to the decomissioned node
+ while (System.currentTimeMillis() <= deadline)
+ {
+ for (int i = 2; i <= cluster.size(); i++)
+ {
+ Object[][] res = cluster.get(i).executeInternal("SELECT active_connections, connection_attempts FROM system_views.internode_outbound WHERE address = '127.0.0.1' AND port = 7012");
+ Assert.assertEquals(1, res.length);
+ Assert.assertEquals(0L, ((Long) res[0][0]).longValue());
+ long attempts = ((Long) res[0][1]).longValue();
+ if (connectionAttempts.get(i) == null)
+ connectionAttempts.put(i, attempts);
+ else
+ Assert.assertEquals(connectionAttempts.get(i), (Long) attempts);
+ }
+ LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(100));
+ }
+ }
+ }
+
+ @Test
+ public void clientConnectionsDuringDecom() throws Throwable
+ {
+ ExecutorService executor = Executors.newFixedThreadPool(1);
+ try (Cluster cluster = builder().withNodes(4)
+ .withConfig(config -> config.with(NETWORK, GOSSIP, NATIVE_PROTOCOL))
+ .start())
{
- populate(cluster);
- naturally = count(cluster);
+ populate(cluster, 0, 100);
+
+ try (com.datastax.driver.core.Cluster client = com.datastax.driver.core.Cluster.builder().addContactPoint("127.0.0.1")
+ .withLoadBalancingPolicy(new RoundRobinPolicy())
+ .build();
+ Session session = client.connect())
+ {
+ CompletableFuture.runAsync(() -> {
+ while (!Thread.currentThread().isInterrupted())
+ {
+ if (client.getMetadata().getAllHosts().size() == cluster.size())
+ return;
+ LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(100));
+ }
+ }, executor).get(1, TimeUnit.MINUTES);
+
+ new DecomissionAction().apply(cluster, cluster.get(1));
+
+ Assert.assertEquals(cluster.size() - 1, client.getMetadata().getAllHosts().size());
+ for (int i = 0; i < 100; i++)
+ {
+ Statement select = new SimpleStatement("select * from " + KEYSPACE + ".tbl WHERE pk = " + i).setConsistencyLevel(com.datastax.driver.core.ConsistencyLevel.ALL);
+ final ResultSet resultSet = session.execute(select);
+ assertRows(RowUtil.toObjects(resultSet), row(i, i, i));
+ }
+ Assert.assertEquals(cluster.size() - 1, client.getMetadata().getAllHosts().size());
+ }
}
+ }
- for (Map.Entry<Integer, Long> e : withBootstrap.entrySet())
- Assert.assertTrue(e.getValue() >= naturally.get(e.getKey()));
+ public static InstanceAction joinRing()
+ {
+ return new JoinRing();
}
- public void populate(ICluster cluster)
+ private static class JoinRing implements InstanceAction
{
- cluster.schemaChange("CREATE KEYSPACE " + KEYSPACE + " WITH replication = {'class': 'SimpleStrategy', 'replication_factor': " + 3 + "};");
- cluster.schemaChange("CREATE TABLE " + KEYSPACE + ".tbl (pk int, ck int, v int, PRIMARY KEY (pk, ck))");
+ public void apply(ICluster<IInvokableInstance> cluster, IInvokableInstance instance)
Review comment:
Sure, that makes sense. Switched to nodetool join.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
[GitHub] [cassandra] ifesdjeen commented on a change in pull request #759: Improve machinery for testing bootstrap and range movements
Posted by GitBox <gi...@apache.org>.
ifesdjeen commented on a change in pull request #759:
URL: https://github.com/apache/cassandra/pull/759#discussion_r508217360
##########
File path: test/distributed/org/apache/cassandra/distributed/action/GossipHelper.java
##########
@@ -0,0 +1,431 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.distributed.action;
+
+import java.io.IOException;
+import java.io.Serializable;
+import java.net.InetSocketAddress;
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.TimeUnit;
+import java.util.stream.Stream;
+
+import net.openhft.chronicle.core.util.SerializableBiFunction;
+import org.apache.cassandra.db.SystemKeyspace;
+import org.apache.cassandra.dht.IPartitioner;
+import org.apache.cassandra.dht.Token;
+import org.apache.cassandra.distributed.api.IInstance;
+import org.apache.cassandra.distributed.api.IInvokableInstance;
+import org.apache.cassandra.distributed.api.IIsolatedExecutor;
+import org.apache.cassandra.distributed.impl.Instance;
+import org.apache.cassandra.distributed.shared.VersionedApplicationState;
+import org.apache.cassandra.gms.ApplicationState;
+import org.apache.cassandra.gms.EndpointState;
+import org.apache.cassandra.gms.Gossiper;
+import org.apache.cassandra.gms.VersionedValue;
+import org.apache.cassandra.io.util.DataInputBuffer;
+import org.apache.cassandra.io.util.DataOutputBuffer;
+import org.apache.cassandra.locator.InetAddressAndPort;
+import org.apache.cassandra.locator.TokenMetadata;
+import org.apache.cassandra.net.MessagingService;
+import org.apache.cassandra.schema.MigrationManager;
+import org.apache.cassandra.service.PendingRangeCalculatorService;
+import org.apache.cassandra.service.StorageService;
+import org.apache.cassandra.utils.FBUtilities;
+
+import static org.apache.cassandra.distributed.impl.DistributedTestSnitch.toCassandraInetAddressAndPort;
+
+public class GossipHelper
+{
+ public static InstanceAction statusToBootstrap(IInvokableInstance newNode)
+ {
+ return (instance) ->
+ {
+ changeGossipState(instance,
+ newNode,
+ Arrays.asList(tokens(newNode),
+ statusBootstrapping(newNode),
+ statusWithPortBootstrapping(newNode)));
+ };
+ }
+
+ public static InstanceAction statusToNormal(IInvokableInstance peer)
+ {
+ return (target) ->
+ {
+ changeGossipState(target,
+ peer,
+ Arrays.asList(tokens(peer),
+ statusNormal(peer),
+ releaseVersion(peer),
+ statusWithPortNormal(peer)));
+ };
+ }
+
+ /**
+ * This method is unsafe and should be used _only_ when gossip is not used or available: it creates versioned values on the
+ * target instance, which means Gossip versioning gets out of sync. Use a safe couterpart at all times when performing _any_
+ * ring movement operations _or_ if Gossip is used.
+ */
+ public static InstanceAction unsafeStatusToNormal(IInstance peer)
+ {
+ return (target) ->
+ {
+ changeGossipState(target,
+ peer,
+ Arrays.asList(unsafeVersionedToken(target,
+ ApplicationState.TOKENS,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).tokens(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeVersionedToken(target,
+ ApplicationState.STATUS,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeVersionedToken(target,
+ ApplicationState.STATUS_WITH_PORT,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeReleaseVersion(target,
+ peer.config().getString("partitioner"),
+ peer.getReleaseVersionString())));
+ };
+ }
+
+ public static InstanceAction statusToLeaving(IInvokableInstance newNode)
+ {
+ return (instance) -> {
+ changeGossipState(instance,
+ newNode,
+ Arrays.asList(tokens(newNode),
+ statusLeaving(newNode),
+ statusWithPortLeaving(newNode)));
+ };
+ }
+
+ public static InstanceAction bootstrap()
+ {
+ return new BootstrapAction();
+ }
+
+ public static InstanceAction bootstrap(boolean joinRing, Duration waitForBootstrap, Duration waitForSchema)
+ {
+ return new BootstrapAction(joinRing, waitForBootstrap, waitForSchema);
+ }
+
+ public static InstanceAction disseminateGossipState(IInvokableInstance newNode)
+ {
+ return new DisseminateGossipState(newNode);
+ }
+
+ public static InstanceAction pullSchemaFrom(IInvokableInstance pullFrom)
+ {
+ return new PullSchemaFrom(pullFrom);
+ }
+
+ private static InstanceAction disableBinary()
+ {
+ return (instance) -> {
+ instance.runOnInstance(StorageService.instance::stopNativeTransport);
+ };
+ }
+
+ private static class DisseminateGossipState implements InstanceAction
+ {
+ final Map<InetSocketAddress, byte[]> gossipState;
+
+ public DisseminateGossipState(IInvokableInstance... from)
+ {
+ gossipState = new HashMap<>();
+ for (IInvokableInstance node : from)
+ {
+ byte[] epBytes = node.callsOnInstance(() -> {
+ EndpointState epState = Gossiper.instance.getEndpointStateForEndpoint(FBUtilities.getBroadcastAddressAndPort());
Review comment:
Just to make sure, I've switched to
```
cluster.run(statusToBootstrap(newInstance), newInstance.config().num());
cluster.run(disseminateGossipState(newInstance));
```
instead of just `statusToBootstrap`, and everything seems to still work. Since each node is calling enquiring its own endpoint, this seems to be fine at first glance, but if you elaborate on where this breaks, I can take another look.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
[GitHub] [cassandra] dcapwell commented on a change in pull request #759: Improve machinery for testing bootstrap and range movements
Posted by GitBox <gi...@apache.org>.
dcapwell commented on a change in pull request #759:
URL: https://github.com/apache/cassandra/pull/759#discussion_r504114411
##########
File path: README.asc
##########
@@ -1,3 +1,4 @@
+
Review comment:
I assume a CI commit? if so I normally do the following
```
git commit --allow-empty -m "trigger ci"
```
##########
File path: src/java/org/apache/cassandra/net/MessagingService.java
##########
@@ -431,6 +431,12 @@ public void shutdown()
public void shutdown(long timeout, TimeUnit units, boolean shutdownGracefully, boolean shutdownExecutors)
{
+ if (isShuttingDown)
Review comment:
I am ok with this, just curious why it was added. I added logic to ignore the error thrown during jvm-dtest shutdown
```
(IgnoreThrowingRunnable) () -> MessagingService.instance().shutdown(1L, MINUTES, false, true)
```
so only curious why triggered this change?
##########
File path: test/distributed/org/apache/cassandra/distributed/action/GossipHelper.java
##########
@@ -0,0 +1,464 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.distributed.action;
+
+
+import java.io.IOException;
+import java.net.InetSocketAddress;
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.TimeUnit;
+import java.util.function.Predicate;
+import java.util.stream.Stream;
+
+import net.openhft.chronicle.core.util.SerializableBiFunction;
+import net.openhft.chronicle.core.util.SerializableConsumer;
+import org.apache.cassandra.db.SystemKeyspace;
+import org.apache.cassandra.dht.IPartitioner;
+import org.apache.cassandra.dht.Token;
+import org.apache.cassandra.distributed.api.ICluster;
+import org.apache.cassandra.distributed.api.IInstance;
+import org.apache.cassandra.distributed.api.IInvokableInstance;
+import org.apache.cassandra.distributed.api.IIsolatedExecutor;
+import org.apache.cassandra.distributed.impl.Instance;
+import org.apache.cassandra.distributed.shared.VersionedApplicationState;
+import org.apache.cassandra.gms.ApplicationState;
+import org.apache.cassandra.gms.EndpointState;
+import org.apache.cassandra.gms.Gossiper;
+import org.apache.cassandra.gms.VersionedValue;
+import org.apache.cassandra.io.util.DataInputBuffer;
+import org.apache.cassandra.io.util.DataOutputBuffer;
+import org.apache.cassandra.locator.InetAddressAndPort;
+import org.apache.cassandra.locator.TokenMetadata;
+import org.apache.cassandra.net.MessagingService;
+import org.apache.cassandra.schema.MigrationManager;
+import org.apache.cassandra.service.PendingRangeCalculatorService;
+import org.apache.cassandra.service.StorageService;
+import org.apache.cassandra.utils.FBUtilities;
+
+import static org.apache.cassandra.distributed.impl.DistributedTestSnitch.toCassandraInetAddressAndPort;
+
+
+public class GossipHelper
+{
+
+ public static ClusterAction clusterAction(InstanceAction action)
+ {
+ return cluster -> cluster.stream().forEach(instance -> {
+ action.apply(cluster, instance);
+ });
+ }
+
+ public static ClusterAction clusterAction(InstanceAction action, Predicate<IInvokableInstance> filter)
+ {
+ return cluster -> cluster.stream().forEach(instance -> {
+ if (filter.test(instance))
+ action.apply(cluster, instance);
+ });
+ }
+
+ public static ClusterAction clusterAction(InstanceAction action, int... instanceIds)
+ {
+ return cluster -> {
+ for (int idx : instanceIds)
+ action.apply(cluster, cluster.get(idx));
+ };
+
+ }
+
+ public static InstanceAction statusToBootstrap(IInvokableInstance newNode)
+ {
+ return new StatusToBootstrap(newNode);
+ }
+
+ public static ClusterAction statusToNormal()
+ {
+ return new ClusterAction()
+ {
+ public void apply(ICluster<IInvokableInstance> cluster)
+ {
+ cluster.stream().forEach((peer) -> {
+ clusterAction(statusToNormal(peer)).apply(cluster);
+ });
+ }
+ };
+ }
+
+ public static InstanceAction statusToNormal(IInvokableInstance newNode)
+ {
+ return new StatusToBootstrap(newNode);
+ }
+
+ public static InstanceAction statusToLeaving(IInvokableInstance newNode)
+ {
+ return new StatusToLeaving(newNode);
+ }
+
+ public static InstanceAction bootstrap()
+ {
+ return new BootstrapAction();
+ }
+
+ public static InstanceAction bootstrap(boolean joinRing, Duration waitForBootstrap, Duration waitForSchema)
+ {
+ return new BootstrapAction(joinRing, waitForBootstrap, waitForSchema);
+ }
+
+ public static InstanceAction disseminateGossipState(IInvokableInstance newNode)
+ {
+ return new DisseminateGossipState(newNode);
+ }
+
+ public static InstanceAction pullSchemaFrom(IInvokableInstance pullFrom)
+ {
+ return new PullSchemaFrom(pullFrom);
+ }
+
+ private static class StatusToBootstrap implements InstanceAction
+ {
+ final IInvokableInstance newNode;
+
+ public StatusToBootstrap(IInvokableInstance newNode)
+ {
+ this.newNode = newNode;
+ }
+
+ public void apply(ICluster<IInvokableInstance> cluster, IInvokableInstance instance)
+ {
+ changeGossipState(instance,
+ newNode,
+ Arrays.asList(tokens(newNode),
+ statusBootstrapping(newNode),
+ statusWithPortBootstrapping(newNode)));
+ }
+ }
+
+ private static class StatusToLeaving implements InstanceAction
+ {
+ final IInvokableInstance newNode;
+
+ public StatusToLeaving(IInvokableInstance newNode)
+ {
+ this.newNode = newNode;
+ }
+
+ public void apply(ICluster<IInvokableInstance> cluster, IInvokableInstance instance)
+ {
+ changeGossipState(instance,
+ newNode,
+ Arrays.asList(tokens(newNode),
+ statusLeaving(newNode),
+ statusWithPortLeaving(newNode)));
+ }
+ }
+
+ private static InstanceAction disableBinary = (cluster, instance) -> {
+ instance.runOnInstance(() -> {
+ StorageService.instance.stopNativeTransport();
+ });
+ };
+
+ public static InstanceAction disableBinary()
+ {
+ return disableBinary;
+ }
+
+ private static class DisseminateGossipState implements InstanceAction
+ {
+ final IInvokableInstance[] from;
+
+ public DisseminateGossipState(IInvokableInstance... from)
+ {
+ this.from = from;
+ }
+
+ public void apply(ICluster<IInvokableInstance> cluster, IInvokableInstance instance)
+ {
+ Map<InetSocketAddress, byte[]> m = new HashMap<>();
+ for (IInvokableInstance node : from)
+ {
+ byte[] epBytes = node.callsOnInstance(() -> {
+ EndpointState epState = Gossiper.instance.getEndpointStateForEndpoint(FBUtilities.getBroadcastAddressAndPort());
+ return toBytes(epState);
+ }).call();
+ m.put(node.broadcastAddress(), epBytes);
+ }
+
+ instance.appliesOnInstance((IIsolatedExecutor.SerializableFunction<Map<InetSocketAddress, byte[]>, Void>)
+ (map) -> {
+ Map<InetAddressAndPort, EndpointState> newState = new HashMap<>();
+ for (Map.Entry<InetSocketAddress, byte[]> e : map.entrySet())
+ newState.put(toCassandraInetAddressAndPort(e.getKey()), fromBytes(e.getValue()));
+
+ Gossiper.runInGossipStageBlocking(() -> {
+ Gossiper.instance.applyStateLocally(newState);
+ });
+ return null;
+ }).apply(m);
+ }
+ }
+
+ public static byte[] toBytes(EndpointState epState)
+ {
+ try (DataOutputBuffer out = new DataOutputBuffer(1024))
+ {
+ EndpointState.serializer.serialize(epState, out, MessagingService.current_version);
+ return out.toByteArray();
+ }
+ catch (IOException e)
+ {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public static EndpointState fromBytes(byte[] bytes)
+ {
+ try (DataInputBuffer in = new DataInputBuffer(bytes))
+ {
+ return EndpointState.serializer.deserialize(in, MessagingService.current_version);
+ }
+ catch (Throwable t)
+ {
+ throw new RuntimeException(t);
+ }
+ }
+
+ private static class PullSchemaFrom implements InstanceAction
+ {
+ final IInvokableInstance pullFrom;
+
+ public PullSchemaFrom(IInvokableInstance pullFrom)
+ {
+ this.pullFrom = pullFrom;
+ }
+
+ public void apply(ICluster<IInvokableInstance> cluster, IInvokableInstance pullTo)
Review comment:
> The idea behind "actions" was in making such things work for multi-version clusters.
But they don't currently as only one GossipHelper is available to the upgrade/mixed-version tests, so these classes/interfaces are in-fact single version only and unsafe in the multi-version cases.
> But other than that - these actions are in fact just functions.
Since these don't work in multi-version clusters why not just use functions? While reading the tests I find the interfaces harder to understand as I need to figure out what they do, but relying on simple functions removes the ambiguity.
##########
File path: src/java/org/apache/cassandra/schema/MigrationManager.java
##########
@@ -40,6 +40,7 @@
import org.apache.cassandra.net.MessagingService;
import org.apache.cassandra.schema.Keyspaces.KeyspacesDiff;
import org.apache.cassandra.utils.FBUtilities;
+import org.assertj.core.util.VisibleForTesting;
Review comment:
don't we normally use the guava one?
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
[GitHub] [cassandra] ifesdjeen commented on a change in pull request #759: Improve machinery for testing bootstrap and range movements
Posted by GitBox <gi...@apache.org>.
ifesdjeen commented on a change in pull request #759:
URL: https://github.com/apache/cassandra/pull/759#discussion_r508228654
##########
File path: test/distributed/org/apache/cassandra/distributed/action/GossipHelper.java
##########
@@ -0,0 +1,431 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.distributed.action;
+
+import java.io.IOException;
+import java.io.Serializable;
+import java.net.InetSocketAddress;
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.TimeUnit;
+import java.util.stream.Stream;
+
+import net.openhft.chronicle.core.util.SerializableBiFunction;
+import org.apache.cassandra.db.SystemKeyspace;
+import org.apache.cassandra.dht.IPartitioner;
+import org.apache.cassandra.dht.Token;
+import org.apache.cassandra.distributed.api.IInstance;
+import org.apache.cassandra.distributed.api.IInvokableInstance;
+import org.apache.cassandra.distributed.api.IIsolatedExecutor;
+import org.apache.cassandra.distributed.impl.Instance;
+import org.apache.cassandra.distributed.shared.VersionedApplicationState;
+import org.apache.cassandra.gms.ApplicationState;
+import org.apache.cassandra.gms.EndpointState;
+import org.apache.cassandra.gms.Gossiper;
+import org.apache.cassandra.gms.VersionedValue;
+import org.apache.cassandra.io.util.DataInputBuffer;
+import org.apache.cassandra.io.util.DataOutputBuffer;
+import org.apache.cassandra.locator.InetAddressAndPort;
+import org.apache.cassandra.locator.TokenMetadata;
+import org.apache.cassandra.net.MessagingService;
+import org.apache.cassandra.schema.MigrationManager;
+import org.apache.cassandra.service.PendingRangeCalculatorService;
+import org.apache.cassandra.service.StorageService;
+import org.apache.cassandra.utils.FBUtilities;
+
+import static org.apache.cassandra.distributed.impl.DistributedTestSnitch.toCassandraInetAddressAndPort;
+
+public class GossipHelper
+{
+ public static InstanceAction statusToBootstrap(IInvokableInstance newNode)
+ {
+ return (instance) ->
+ {
+ changeGossipState(instance,
+ newNode,
+ Arrays.asList(tokens(newNode),
+ statusBootstrapping(newNode),
+ statusWithPortBootstrapping(newNode)));
+ };
+ }
+
+ public static InstanceAction statusToNormal(IInvokableInstance peer)
+ {
+ return (target) ->
+ {
+ changeGossipState(target,
+ peer,
+ Arrays.asList(tokens(peer),
+ statusNormal(peer),
+ releaseVersion(peer),
+ statusWithPortNormal(peer)));
+ };
+ }
+
+ /**
+ * This method is unsafe and should be used _only_ when gossip is not used or available: it creates versioned values on the
+ * target instance, which means Gossip versioning gets out of sync. Use a safe couterpart at all times when performing _any_
+ * ring movement operations _or_ if Gossip is used.
+ */
+ public static InstanceAction unsafeStatusToNormal(IInstance peer)
+ {
+ return (target) ->
+ {
+ changeGossipState(target,
+ peer,
+ Arrays.asList(unsafeVersionedToken(target,
+ ApplicationState.TOKENS,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).tokens(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeVersionedToken(target,
+ ApplicationState.STATUS,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeVersionedToken(target,
+ ApplicationState.STATUS_WITH_PORT,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeReleaseVersion(target,
+ peer.config().getString("partitioner"),
+ peer.getReleaseVersionString())));
+ };
+ }
+
+ public static InstanceAction statusToLeaving(IInvokableInstance newNode)
+ {
+ return (instance) -> {
+ changeGossipState(instance,
+ newNode,
+ Arrays.asList(tokens(newNode),
+ statusLeaving(newNode),
+ statusWithPortLeaving(newNode)));
+ };
+ }
+
+ public static InstanceAction bootstrap()
+ {
+ return new BootstrapAction();
+ }
+
+ public static InstanceAction bootstrap(boolean joinRing, Duration waitForBootstrap, Duration waitForSchema)
+ {
+ return new BootstrapAction(joinRing, waitForBootstrap, waitForSchema);
+ }
+
+ public static InstanceAction disseminateGossipState(IInvokableInstance newNode)
+ {
+ return new DisseminateGossipState(newNode);
+ }
+
+ public static InstanceAction pullSchemaFrom(IInvokableInstance pullFrom)
+ {
+ return new PullSchemaFrom(pullFrom);
+ }
+
+ private static InstanceAction disableBinary()
+ {
+ return (instance) -> {
+ instance.runOnInstance(StorageService.instance::stopNativeTransport);
+ };
+ }
+
+ private static class DisseminateGossipState implements InstanceAction
+ {
+ final Map<InetSocketAddress, byte[]> gossipState;
+
+ public DisseminateGossipState(IInvokableInstance... from)
+ {
+ gossipState = new HashMap<>();
+ for (IInvokableInstance node : from)
+ {
+ byte[] epBytes = node.callsOnInstance(() -> {
+ EndpointState epState = Gossiper.instance.getEndpointStateForEndpoint(FBUtilities.getBroadcastAddressAndPort());
+ return toBytes(epState);
+ }).call();
+ gossipState.put(node.broadcastAddress(), epBytes);
+ }
+ }
+
+ public void accept(IInvokableInstance instance)
+ {
+ instance.appliesOnInstance((IIsolatedExecutor.SerializableFunction<Map<InetSocketAddress, byte[]>, Void>)
+ (map) -> {
+ Map<InetAddressAndPort, EndpointState> newState = new HashMap<>();
+ for (Map.Entry<InetSocketAddress, byte[]> e : map.entrySet())
+ newState.put(toCassandraInetAddressAndPort(e.getKey()), fromBytes(e.getValue()));
+
+ Gossiper.runInGossipStageBlocking(() -> {
+ Gossiper.instance.applyStateLocally(newState);
+ });
+ return null;
+ }).apply(gossipState);
+ }
+ }
+
+ public static byte[] toBytes(EndpointState epState)
+ {
+ try (DataOutputBuffer out = new DataOutputBuffer(1024))
+ {
+ EndpointState.serializer.serialize(epState, out, MessagingService.current_version);
+ return out.toByteArray();
+ }
+ catch (IOException e)
+ {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public static EndpointState fromBytes(byte[] bytes)
+ {
+ try (DataInputBuffer in = new DataInputBuffer(bytes))
+ {
+ return EndpointState.serializer.deserialize(in, MessagingService.current_version);
+ }
+ catch (Throwable t)
+ {
+ throw new RuntimeException(t);
+ }
+ }
+
+ private static class PullSchemaFrom implements InstanceAction
+ {
+ final InetSocketAddress pullFrom;
+
+ public PullSchemaFrom(IInvokableInstance pullFrom)
+ {
+ this.pullFrom = pullFrom.broadcastAddress();;
+ }
+
+ public void accept(IInvokableInstance pullTo)
+ {
+ pullTo.acceptsOnInstance((InetSocketAddress pullFrom) -> {
+ InetAddressAndPort endpoint = toCassandraInetAddressAndPort(pullFrom);
+ EndpointState state = Gossiper.instance.getEndpointStateForEndpoint(endpoint);
+ MigrationManager.scheduleSchemaPull(endpoint, state);
+ MigrationManager.waitUntilReadyForBootstrap();
+ }).accept(pullFrom);
+ }
+ }
+
+ private static class BootstrapAction implements InstanceAction, Serializable
+ {
+ private final boolean joinRing;
+ private final Duration waitForBootstrap;
+ private final Duration waitForSchema;
+
+ public BootstrapAction()
+ {
+ this(true, Duration.ofMinutes(10), Duration.ofSeconds(10));
+ }
+
+ public BootstrapAction(boolean joinRing, Duration waitForBootstrap, Duration waitForSchema)
+ {
+ this.joinRing = joinRing;
+ this.waitForBootstrap = waitForBootstrap;
+ this.waitForSchema = waitForSchema;
+ }
+
+ public void accept(IInvokableInstance instance)
+ {
+ instance.appliesOnInstance((String partitionerString, String tokenString) -> {
+ IPartitioner partitioner = FBUtilities.newPartitioner(partitionerString);
+ List<Token> tokens = Collections.singletonList(partitioner.getTokenFactory().fromString(tokenString));
+ try
+ {
+ SystemKeyspace.setBootstrapState(SystemKeyspace.BootstrapState.IN_PROGRESS);
+ StorageService.instance.waitForSchema((int) waitForSchema.toMillis());
Review comment:
Oh, well spotted! I agree that the implementation of `waitForSchema` looks quite spotty: each attempt is a 1s sleep, but at the same time each attempt increments a counter by 1000:
```
for (int i = 0; i < delay; i += 1000)
```
I agree that this is something we should address though. Should we open a separate ticket for this?
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
[GitHub] [cassandra] ifesdjeen commented on a change in pull request #759: Improve machinery for testing bootstrap and range movements
Posted by GitBox <gi...@apache.org>.
ifesdjeen commented on a change in pull request #759:
URL: https://github.com/apache/cassandra/pull/759#discussion_r509131387
##########
File path: test/distributed/org/apache/cassandra/distributed/action/GossipHelper.java
##########
@@ -0,0 +1,431 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.distributed.action;
+
+import java.io.IOException;
+import java.io.Serializable;
+import java.net.InetSocketAddress;
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.TimeUnit;
+import java.util.stream.Stream;
+
+import net.openhft.chronicle.core.util.SerializableBiFunction;
+import org.apache.cassandra.db.SystemKeyspace;
+import org.apache.cassandra.dht.IPartitioner;
+import org.apache.cassandra.dht.Token;
+import org.apache.cassandra.distributed.api.IInstance;
+import org.apache.cassandra.distributed.api.IInvokableInstance;
+import org.apache.cassandra.distributed.api.IIsolatedExecutor;
+import org.apache.cassandra.distributed.impl.Instance;
+import org.apache.cassandra.distributed.shared.VersionedApplicationState;
+import org.apache.cassandra.gms.ApplicationState;
+import org.apache.cassandra.gms.EndpointState;
+import org.apache.cassandra.gms.Gossiper;
+import org.apache.cassandra.gms.VersionedValue;
+import org.apache.cassandra.io.util.DataInputBuffer;
+import org.apache.cassandra.io.util.DataOutputBuffer;
+import org.apache.cassandra.locator.InetAddressAndPort;
+import org.apache.cassandra.locator.TokenMetadata;
+import org.apache.cassandra.net.MessagingService;
+import org.apache.cassandra.schema.MigrationManager;
+import org.apache.cassandra.service.PendingRangeCalculatorService;
+import org.apache.cassandra.service.StorageService;
+import org.apache.cassandra.utils.FBUtilities;
+
+import static org.apache.cassandra.distributed.impl.DistributedTestSnitch.toCassandraInetAddressAndPort;
+
+public class GossipHelper
+{
+ public static InstanceAction statusToBootstrap(IInvokableInstance newNode)
+ {
+ return (instance) ->
+ {
+ changeGossipState(instance,
+ newNode,
+ Arrays.asList(tokens(newNode),
+ statusBootstrapping(newNode),
+ statusWithPortBootstrapping(newNode)));
+ };
+ }
+
+ public static InstanceAction statusToNormal(IInvokableInstance peer)
+ {
+ return (target) ->
+ {
+ changeGossipState(target,
+ peer,
+ Arrays.asList(tokens(peer),
+ statusNormal(peer),
+ releaseVersion(peer),
+ statusWithPortNormal(peer)));
+ };
+ }
+
+ /**
+ * This method is unsafe and should be used _only_ when gossip is not used or available: it creates versioned values on the
+ * target instance, which means Gossip versioning gets out of sync. Use a safe couterpart at all times when performing _any_
+ * ring movement operations _or_ if Gossip is used.
+ */
+ public static InstanceAction unsafeStatusToNormal(IInstance peer)
+ {
+ return (target) ->
+ {
+ changeGossipState(target,
+ peer,
+ Arrays.asList(unsafeVersionedToken(target,
+ ApplicationState.TOKENS,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).tokens(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeVersionedToken(target,
+ ApplicationState.STATUS,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeVersionedToken(target,
+ ApplicationState.STATUS_WITH_PORT,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeReleaseVersion(target,
+ peer.config().getString("partitioner"),
+ peer.getReleaseVersionString())));
+ };
+ }
+
+ public static InstanceAction statusToLeaving(IInvokableInstance newNode)
+ {
+ return (instance) -> {
+ changeGossipState(instance,
+ newNode,
+ Arrays.asList(tokens(newNode),
+ statusLeaving(newNode),
+ statusWithPortLeaving(newNode)));
+ };
+ }
+
+ public static InstanceAction bootstrap()
+ {
+ return new BootstrapAction();
+ }
+
+ public static InstanceAction bootstrap(boolean joinRing, Duration waitForBootstrap, Duration waitForSchema)
+ {
+ return new BootstrapAction(joinRing, waitForBootstrap, waitForSchema);
+ }
+
+ public static InstanceAction disseminateGossipState(IInvokableInstance newNode)
+ {
+ return new DisseminateGossipState(newNode);
+ }
+
+ public static InstanceAction pullSchemaFrom(IInvokableInstance pullFrom)
+ {
+ return new PullSchemaFrom(pullFrom);
+ }
+
+ private static InstanceAction disableBinary()
+ {
+ return (instance) -> {
+ instance.runOnInstance(StorageService.instance::stopNativeTransport);
+ };
+ }
+
+ private static class DisseminateGossipState implements InstanceAction
+ {
+ final Map<InetSocketAddress, byte[]> gossipState;
+
+ public DisseminateGossipState(IInvokableInstance... from)
+ {
+ gossipState = new HashMap<>();
+ for (IInvokableInstance node : from)
+ {
+ byte[] epBytes = node.callsOnInstance(() -> {
+ EndpointState epState = Gossiper.instance.getEndpointStateForEndpoint(FBUtilities.getBroadcastAddressAndPort());
+ return toBytes(epState);
+ }).call();
+ gossipState.put(node.broadcastAddress(), epBytes);
+ }
+ }
+
+ public void accept(IInvokableInstance instance)
+ {
+ instance.appliesOnInstance((IIsolatedExecutor.SerializableFunction<Map<InetSocketAddress, byte[]>, Void>)
+ (map) -> {
+ Map<InetAddressAndPort, EndpointState> newState = new HashMap<>();
+ for (Map.Entry<InetSocketAddress, byte[]> e : map.entrySet())
+ newState.put(toCassandraInetAddressAndPort(e.getKey()), fromBytes(e.getValue()));
+
+ Gossiper.runInGossipStageBlocking(() -> {
+ Gossiper.instance.applyStateLocally(newState);
+ });
+ return null;
+ }).apply(gossipState);
+ }
+ }
+
+ public static byte[] toBytes(EndpointState epState)
+ {
+ try (DataOutputBuffer out = new DataOutputBuffer(1024))
+ {
+ EndpointState.serializer.serialize(epState, out, MessagingService.current_version);
+ return out.toByteArray();
+ }
+ catch (IOException e)
+ {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public static EndpointState fromBytes(byte[] bytes)
+ {
+ try (DataInputBuffer in = new DataInputBuffer(bytes))
+ {
+ return EndpointState.serializer.deserialize(in, MessagingService.current_version);
+ }
+ catch (Throwable t)
+ {
+ throw new RuntimeException(t);
+ }
+ }
+
+ private static class PullSchemaFrom implements InstanceAction
+ {
+ final InetSocketAddress pullFrom;
+
+ public PullSchemaFrom(IInvokableInstance pullFrom)
+ {
+ this.pullFrom = pullFrom.broadcastAddress();;
+ }
+
+ public void accept(IInvokableInstance pullTo)
+ {
+ pullTo.acceptsOnInstance((InetSocketAddress pullFrom) -> {
+ InetAddressAndPort endpoint = toCassandraInetAddressAndPort(pullFrom);
+ EndpointState state = Gossiper.instance.getEndpointStateForEndpoint(endpoint);
+ MigrationManager.scheduleSchemaPull(endpoint, state);
+ MigrationManager.waitUntilReadyForBootstrap();
+ }).accept(pullFrom);
+ }
+ }
+
+ private static class BootstrapAction implements InstanceAction, Serializable
+ {
+ private final boolean joinRing;
+ private final Duration waitForBootstrap;
+ private final Duration waitForSchema;
+
+ public BootstrapAction()
+ {
+ this(true, Duration.ofMinutes(10), Duration.ofSeconds(10));
+ }
+
+ public BootstrapAction(boolean joinRing, Duration waitForBootstrap, Duration waitForSchema)
+ {
+ this.joinRing = joinRing;
+ this.waitForBootstrap = waitForBootstrap;
+ this.waitForSchema = waitForSchema;
+ }
+
+ public void accept(IInvokableInstance instance)
+ {
+ instance.appliesOnInstance((String partitionerString, String tokenString) -> {
Review comment:
Sure, I think generally it's good to reuse existing code and means.
Unfortunately, in this case I had to not use `surveyMode` and `auto_bootstrap` as means of passing down the calls since they can only be set once per node (unless we introduce some hacks). We may also want to rethink usage of `cassandra.join_ring` in the future, since it can only be set once per node as well. I'll leave this for some future patch though.
Your suggestion is now implemented here: https://github.com/ifesdjeen/cassandra/commit/b654aec364837c45d01f6fa0712cea4cd4bf920a
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
[GitHub] [cassandra] ifesdjeen commented on a change in pull request #759: Improve machinery for testing bootstrap and range movements
Posted by GitBox <gi...@apache.org>.
ifesdjeen commented on a change in pull request #759:
URL: https://github.com/apache/cassandra/pull/759#discussion_r509131387
##########
File path: test/distributed/org/apache/cassandra/distributed/action/GossipHelper.java
##########
@@ -0,0 +1,431 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.distributed.action;
+
+import java.io.IOException;
+import java.io.Serializable;
+import java.net.InetSocketAddress;
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.TimeUnit;
+import java.util.stream.Stream;
+
+import net.openhft.chronicle.core.util.SerializableBiFunction;
+import org.apache.cassandra.db.SystemKeyspace;
+import org.apache.cassandra.dht.IPartitioner;
+import org.apache.cassandra.dht.Token;
+import org.apache.cassandra.distributed.api.IInstance;
+import org.apache.cassandra.distributed.api.IInvokableInstance;
+import org.apache.cassandra.distributed.api.IIsolatedExecutor;
+import org.apache.cassandra.distributed.impl.Instance;
+import org.apache.cassandra.distributed.shared.VersionedApplicationState;
+import org.apache.cassandra.gms.ApplicationState;
+import org.apache.cassandra.gms.EndpointState;
+import org.apache.cassandra.gms.Gossiper;
+import org.apache.cassandra.gms.VersionedValue;
+import org.apache.cassandra.io.util.DataInputBuffer;
+import org.apache.cassandra.io.util.DataOutputBuffer;
+import org.apache.cassandra.locator.InetAddressAndPort;
+import org.apache.cassandra.locator.TokenMetadata;
+import org.apache.cassandra.net.MessagingService;
+import org.apache.cassandra.schema.MigrationManager;
+import org.apache.cassandra.service.PendingRangeCalculatorService;
+import org.apache.cassandra.service.StorageService;
+import org.apache.cassandra.utils.FBUtilities;
+
+import static org.apache.cassandra.distributed.impl.DistributedTestSnitch.toCassandraInetAddressAndPort;
+
+public class GossipHelper
+{
+ public static InstanceAction statusToBootstrap(IInvokableInstance newNode)
+ {
+ return (instance) ->
+ {
+ changeGossipState(instance,
+ newNode,
+ Arrays.asList(tokens(newNode),
+ statusBootstrapping(newNode),
+ statusWithPortBootstrapping(newNode)));
+ };
+ }
+
+ public static InstanceAction statusToNormal(IInvokableInstance peer)
+ {
+ return (target) ->
+ {
+ changeGossipState(target,
+ peer,
+ Arrays.asList(tokens(peer),
+ statusNormal(peer),
+ releaseVersion(peer),
+ statusWithPortNormal(peer)));
+ };
+ }
+
+ /**
+ * This method is unsafe and should be used _only_ when gossip is not used or available: it creates versioned values on the
+ * target instance, which means Gossip versioning gets out of sync. Use a safe couterpart at all times when performing _any_
+ * ring movement operations _or_ if Gossip is used.
+ */
+ public static InstanceAction unsafeStatusToNormal(IInstance peer)
+ {
+ return (target) ->
+ {
+ changeGossipState(target,
+ peer,
+ Arrays.asList(unsafeVersionedToken(target,
+ ApplicationState.TOKENS,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).tokens(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeVersionedToken(target,
+ ApplicationState.STATUS,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeVersionedToken(target,
+ ApplicationState.STATUS_WITH_PORT,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeReleaseVersion(target,
+ peer.config().getString("partitioner"),
+ peer.getReleaseVersionString())));
+ };
+ }
+
+ public static InstanceAction statusToLeaving(IInvokableInstance newNode)
+ {
+ return (instance) -> {
+ changeGossipState(instance,
+ newNode,
+ Arrays.asList(tokens(newNode),
+ statusLeaving(newNode),
+ statusWithPortLeaving(newNode)));
+ };
+ }
+
+ public static InstanceAction bootstrap()
+ {
+ return new BootstrapAction();
+ }
+
+ public static InstanceAction bootstrap(boolean joinRing, Duration waitForBootstrap, Duration waitForSchema)
+ {
+ return new BootstrapAction(joinRing, waitForBootstrap, waitForSchema);
+ }
+
+ public static InstanceAction disseminateGossipState(IInvokableInstance newNode)
+ {
+ return new DisseminateGossipState(newNode);
+ }
+
+ public static InstanceAction pullSchemaFrom(IInvokableInstance pullFrom)
+ {
+ return new PullSchemaFrom(pullFrom);
+ }
+
+ private static InstanceAction disableBinary()
+ {
+ return (instance) -> {
+ instance.runOnInstance(StorageService.instance::stopNativeTransport);
+ };
+ }
+
+ private static class DisseminateGossipState implements InstanceAction
+ {
+ final Map<InetSocketAddress, byte[]> gossipState;
+
+ public DisseminateGossipState(IInvokableInstance... from)
+ {
+ gossipState = new HashMap<>();
+ for (IInvokableInstance node : from)
+ {
+ byte[] epBytes = node.callsOnInstance(() -> {
+ EndpointState epState = Gossiper.instance.getEndpointStateForEndpoint(FBUtilities.getBroadcastAddressAndPort());
+ return toBytes(epState);
+ }).call();
+ gossipState.put(node.broadcastAddress(), epBytes);
+ }
+ }
+
+ public void accept(IInvokableInstance instance)
+ {
+ instance.appliesOnInstance((IIsolatedExecutor.SerializableFunction<Map<InetSocketAddress, byte[]>, Void>)
+ (map) -> {
+ Map<InetAddressAndPort, EndpointState> newState = new HashMap<>();
+ for (Map.Entry<InetSocketAddress, byte[]> e : map.entrySet())
+ newState.put(toCassandraInetAddressAndPort(e.getKey()), fromBytes(e.getValue()));
+
+ Gossiper.runInGossipStageBlocking(() -> {
+ Gossiper.instance.applyStateLocally(newState);
+ });
+ return null;
+ }).apply(gossipState);
+ }
+ }
+
+ public static byte[] toBytes(EndpointState epState)
+ {
+ try (DataOutputBuffer out = new DataOutputBuffer(1024))
+ {
+ EndpointState.serializer.serialize(epState, out, MessagingService.current_version);
+ return out.toByteArray();
+ }
+ catch (IOException e)
+ {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public static EndpointState fromBytes(byte[] bytes)
+ {
+ try (DataInputBuffer in = new DataInputBuffer(bytes))
+ {
+ return EndpointState.serializer.deserialize(in, MessagingService.current_version);
+ }
+ catch (Throwable t)
+ {
+ throw new RuntimeException(t);
+ }
+ }
+
+ private static class PullSchemaFrom implements InstanceAction
+ {
+ final InetSocketAddress pullFrom;
+
+ public PullSchemaFrom(IInvokableInstance pullFrom)
+ {
+ this.pullFrom = pullFrom.broadcastAddress();;
+ }
+
+ public void accept(IInvokableInstance pullTo)
+ {
+ pullTo.acceptsOnInstance((InetSocketAddress pullFrom) -> {
+ InetAddressAndPort endpoint = toCassandraInetAddressAndPort(pullFrom);
+ EndpointState state = Gossiper.instance.getEndpointStateForEndpoint(endpoint);
+ MigrationManager.scheduleSchemaPull(endpoint, state);
+ MigrationManager.waitUntilReadyForBootstrap();
+ }).accept(pullFrom);
+ }
+ }
+
+ private static class BootstrapAction implements InstanceAction, Serializable
+ {
+ private final boolean joinRing;
+ private final Duration waitForBootstrap;
+ private final Duration waitForSchema;
+
+ public BootstrapAction()
+ {
+ this(true, Duration.ofMinutes(10), Duration.ofSeconds(10));
+ }
+
+ public BootstrapAction(boolean joinRing, Duration waitForBootstrap, Duration waitForSchema)
+ {
+ this.joinRing = joinRing;
+ this.waitForBootstrap = waitForBootstrap;
+ this.waitForSchema = waitForSchema;
+ }
+
+ public void accept(IInvokableInstance instance)
+ {
+ instance.appliesOnInstance((String partitionerString, String tokenString) -> {
Review comment:
Sure, I think generally it's good to reuse existing code and means.
Unfortunately, in this case I had to not use `surveyMode` and `auto_bootstrap` as means of passing down the calls since they can only be set once per node (unless we introduce some hacks). We may also want to rethink usage of `cassandra.join_ring` in the future, since it can only be set once per node as well. I'll leave this for some future patch though.
Your suggestion is now implemented here: https://github.com/ifesdjeen/cassandra/commit/137e44e5260648d1cb1a2b81f32269ec22037738
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
[GitHub] [cassandra] smiklosovic closed pull request #759: Improve machinery for testing bootstrap and range movements
Posted by GitBox <gi...@apache.org>.
smiklosovic closed pull request #759:
URL: https://github.com/apache/cassandra/pull/759
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
[GitHub] [cassandra] dcapwell commented on a change in pull request #759: Improve machinery for testing bootstrap and range movements
Posted by GitBox <gi...@apache.org>.
dcapwell commented on a change in pull request #759:
URL: https://github.com/apache/cassandra/pull/759#discussion_r504833951
##########
File path: test/distributed/org/apache/cassandra/distributed/test/BootstrapTest.java
##########
@@ -18,85 +18,244 @@
package org.apache.cassandra.distributed.test;
+import java.net.InetSocketAddress;
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.HashSet;
import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.locks.LockSupport;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.junit.Assert;
import org.junit.Test;
+import com.datastax.driver.core.ResultSet;
+import com.datastax.driver.core.Session;
+import com.datastax.driver.core.SimpleStatement;
+import com.datastax.driver.core.Statement;
+import com.datastax.driver.core.policies.RoundRobinPolicy;
+import org.apache.cassandra.dht.Range;
+import org.apache.cassandra.dht.Token;
import org.apache.cassandra.distributed.Cluster;
import org.apache.cassandra.distributed.api.ConsistencyLevel;
import org.apache.cassandra.distributed.api.ICluster;
import org.apache.cassandra.distributed.api.IInstanceConfig;
+import org.apache.cassandra.distributed.api.IInvokableInstance;
import org.apache.cassandra.distributed.api.TokenSupplier;
+import org.apache.cassandra.distributed.impl.DistributedTestSnitch;
+import org.apache.cassandra.distributed.impl.RowUtil;
import org.apache.cassandra.distributed.shared.NetworkTopology;
+import org.apache.cassandra.locator.EndpointsForRange;
+import org.apache.cassandra.locator.InetAddressAndPort;
+import org.apache.cassandra.service.StorageService;
+import static java.util.Arrays.*;
+import static org.apache.cassandra.distributed.action.GossipHelper.bootstrap;
+import static org.apache.cassandra.distributed.action.GossipHelper.decomission;
+import static org.apache.cassandra.distributed.action.GossipHelper.disseminateGossipState;
+import static org.apache.cassandra.distributed.action.GossipHelper.pullSchemaFrom;
+import static org.apache.cassandra.distributed.action.GossipHelper.statusToBootstrap;
import static org.apache.cassandra.distributed.api.Feature.GOSSIP;
+import static org.apache.cassandra.distributed.api.Feature.NATIVE_PROTOCOL;
import static org.apache.cassandra.distributed.api.Feature.NETWORK;
+import static org.apache.cassandra.distributed.shared.AssertUtils.assertRows;
+import static org.apache.cassandra.distributed.shared.AssertUtils.row;
-// TODO: this test should be removed after running in-jvm dtests is set up via the shared API repository
public class BootstrapTest extends TestBaseImpl
{
-
@Test
public void bootstrapTest() throws Throwable
{
int originalNodeCount = 2;
int expandedNodeCount = originalNodeCount + 1;
- Cluster.Builder builder = builder().withNodes(originalNodeCount)
- .withTokenSupplier(TokenSupplier.evenlyDistributedTokens(expandedNodeCount))
- .withNodeIdTopology(NetworkTopology.singleDcNetworkTopology(expandedNodeCount, "dc0", "rack0"))
- .withConfig(config -> config.with(NETWORK, GOSSIP));
-
- Map<Integer, Long> withBootstrap = null;
- Map<Integer, Long> naturally = null;
- try (Cluster cluster = builder.withNodes(originalNodeCount).start())
+
+ try (Cluster cluster = builder().withNodes(originalNodeCount)
+ .withTokenSupplier(TokenSupplier.evenlyDistributedTokens(expandedNodeCount))
+ .withNodeIdTopology(NetworkTopology.singleDcNetworkTopology(expandedNodeCount, "dc0", "rack0"))
+ .withConfig(config -> config.with(NETWORK, GOSSIP))
+ .start())
{
- populate(cluster);
+ populate(cluster,0, 100);
IInstanceConfig config = cluster.newInstanceConfig();
- config.set("auto_bootstrap", true);
-
- cluster.bootstrap(config).startup();
+ IInvokableInstance newInstance = cluster.initialize(config);
+ withJoinRing(false, () -> newInstance.startup(cluster));
- cluster.stream().forEach(instance -> {
- instance.nodetool("cleanup", KEYSPACE, "tbl");
- });
+ cluster.forEach(statusToBootstrap(newInstance));
+ cluster.run(asList(pullSchemaFrom(cluster.get(1)),
Review comment:
comment was lost in the refactor, reposting
If you turn off joining the ring and disable autoboostrap (dtest default) then when you call `nodetool join` it will join the ring without bootstrapping (since autoboostrap=false). This test runs in that state, but then tries to bootstrap (which I don't think is currently possible), so feels like its testing a state we don't allow an operator to put us in?
If we add back auto_bootstrap=true then this logic can be replaced by
```
IInstanceConfig config = cluster.newInstanceConfig();
config.set("auto_bootstrap", true);
IInvokableInstance newInstance = cluster.initialize(config);
withJoinRing(false, () -> newInstance.startup(cluster));
newInstance.nodetoolResult("join").asserts().success();
```
I took a stab and changed the test to do join in https://github.com/dcapwell/cassandra/commit/935f78b101484f6dfee473fd5375a31761f02b39
##########
File path: test/distributed/org/apache/cassandra/distributed/test/BootstrapTest.java
##########
@@ -18,85 +18,244 @@
package org.apache.cassandra.distributed.test;
+import java.net.InetSocketAddress;
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.HashSet;
import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.locks.LockSupport;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.junit.Assert;
import org.junit.Test;
+import com.datastax.driver.core.ResultSet;
+import com.datastax.driver.core.Session;
+import com.datastax.driver.core.SimpleStatement;
+import com.datastax.driver.core.Statement;
+import com.datastax.driver.core.policies.RoundRobinPolicy;
+import org.apache.cassandra.dht.Range;
+import org.apache.cassandra.dht.Token;
import org.apache.cassandra.distributed.Cluster;
import org.apache.cassandra.distributed.api.ConsistencyLevel;
import org.apache.cassandra.distributed.api.ICluster;
import org.apache.cassandra.distributed.api.IInstanceConfig;
+import org.apache.cassandra.distributed.api.IInvokableInstance;
import org.apache.cassandra.distributed.api.TokenSupplier;
+import org.apache.cassandra.distributed.impl.DistributedTestSnitch;
+import org.apache.cassandra.distributed.impl.RowUtil;
import org.apache.cassandra.distributed.shared.NetworkTopology;
+import org.apache.cassandra.locator.EndpointsForRange;
+import org.apache.cassandra.locator.InetAddressAndPort;
+import org.apache.cassandra.service.StorageService;
+import static java.util.Arrays.*;
+import static org.apache.cassandra.distributed.action.GossipHelper.bootstrap;
+import static org.apache.cassandra.distributed.action.GossipHelper.decomission;
+import static org.apache.cassandra.distributed.action.GossipHelper.disseminateGossipState;
+import static org.apache.cassandra.distributed.action.GossipHelper.pullSchemaFrom;
+import static org.apache.cassandra.distributed.action.GossipHelper.statusToBootstrap;
import static org.apache.cassandra.distributed.api.Feature.GOSSIP;
+import static org.apache.cassandra.distributed.api.Feature.NATIVE_PROTOCOL;
import static org.apache.cassandra.distributed.api.Feature.NETWORK;
+import static org.apache.cassandra.distributed.shared.AssertUtils.assertRows;
+import static org.apache.cassandra.distributed.shared.AssertUtils.row;
-// TODO: this test should be removed after running in-jvm dtests is set up via the shared API repository
public class BootstrapTest extends TestBaseImpl
Review comment:
This class is too slow for CI, can we split the tests across multiple files?
```
[junit-timeout] Testsuite: org.apache.cassandra.distributed.test.BootstrapTest
[junit-timeout] Testsuite: org.apache.cassandra.distributed.test.BootstrapTest Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0 sec
[junit-timeout]
[junit-timeout] Testcase: org.apache.cassandra.distributed.test.BootstrapTest:internodeConnectionsDuringDecom: Caused an ERROR
[junit-timeout] Timeout occurred. Please note the time in the report does not reflect the time until the timeout.
[junit-timeout] junit.framework.AssertionFailedError: Timeout occurred. Please note the time in the report does not reflect the time until the timeout.
[junit-timeout] at java.util.Vector.forEach(Vector.java:1275)
[junit-timeout] at java.util.Vector.forEach(Vector.java:1275)
[junit-timeout] at java.lang.Thread.run(Thread.java:748)
[junit-timeout]
[junit-timeout]
[junit-timeout] Test org.apache.cassandra.distributed.test.BootstrapTest FAILED (timeout)
BUILD FAILED
/Users/davidcapwell/src/github/apache/team/alex_petrov-trunk/build.xml:2030: The following error occurred while executing this line:
/Users/davidcapwell/src/github/apache/team/alex_petrov-trunk/build.xml:1911: Some test(s) failed.
Total time: 7 minutes 1 second
```
I an the test in a loop to see if it would be flaky and the test ended up timing out.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
[GitHub] [cassandra] ifesdjeen commented on a change in pull request #759: Improve machinery for testing bootstrap and range movements
Posted by GitBox <gi...@apache.org>.
ifesdjeen commented on a change in pull request #759:
URL: https://github.com/apache/cassandra/pull/759#discussion_r504543218
##########
File path: test/distributed/org/apache/cassandra/distributed/action/GossipHelper.java
##########
@@ -0,0 +1,464 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.distributed.action;
+
+
+import java.io.IOException;
+import java.net.InetSocketAddress;
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.TimeUnit;
+import java.util.function.Predicate;
+import java.util.stream.Stream;
+
+import net.openhft.chronicle.core.util.SerializableBiFunction;
+import net.openhft.chronicle.core.util.SerializableConsumer;
+import org.apache.cassandra.db.SystemKeyspace;
+import org.apache.cassandra.dht.IPartitioner;
+import org.apache.cassandra.dht.Token;
+import org.apache.cassandra.distributed.api.ICluster;
+import org.apache.cassandra.distributed.api.IInstance;
+import org.apache.cassandra.distributed.api.IInvokableInstance;
+import org.apache.cassandra.distributed.api.IIsolatedExecutor;
+import org.apache.cassandra.distributed.impl.Instance;
+import org.apache.cassandra.distributed.shared.VersionedApplicationState;
+import org.apache.cassandra.gms.ApplicationState;
+import org.apache.cassandra.gms.EndpointState;
+import org.apache.cassandra.gms.Gossiper;
+import org.apache.cassandra.gms.VersionedValue;
+import org.apache.cassandra.io.util.DataInputBuffer;
+import org.apache.cassandra.io.util.DataOutputBuffer;
+import org.apache.cassandra.locator.InetAddressAndPort;
+import org.apache.cassandra.locator.TokenMetadata;
+import org.apache.cassandra.net.MessagingService;
+import org.apache.cassandra.schema.MigrationManager;
+import org.apache.cassandra.service.PendingRangeCalculatorService;
+import org.apache.cassandra.service.StorageService;
+import org.apache.cassandra.utils.FBUtilities;
+
+import static org.apache.cassandra.distributed.impl.DistributedTestSnitch.toCassandraInetAddressAndPort;
+
+
+public class GossipHelper
+{
+
+ public static ClusterAction clusterAction(InstanceAction action)
Review comment:
Since this conversation is getting lengthier, moving it to jira.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
[GitHub] [cassandra] ifesdjeen commented on a change in pull request #759: Improve machinery for testing bootstrap and range movements
Posted by GitBox <gi...@apache.org>.
ifesdjeen commented on a change in pull request #759:
URL: https://github.com/apache/cassandra/pull/759#discussion_r504033615
##########
File path: test/distributed/org/apache/cassandra/distributed/impl/Instance.java
##########
@@ -438,24 +457,27 @@ public void startup(ICluster cluster)
// TODO: this is more than just gossip
if (config.has(GOSSIP))
{
- StorageService.instance.initServer();
+ StorageService.instance.registerDaemon(CassandraDaemon.getInstanceForTesting());
+ StorageService.instance.initServer(StorageService.RING_DELAY,
+ !startupOptions.contains(StartupOption.SKIP_RING_JOIN));
Review comment:
Switched to use the prop.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
[GitHub] [cassandra] ifesdjeen commented on a change in pull request #759: Improve machinery for testing bootstrap and range movements
Posted by GitBox <gi...@apache.org>.
ifesdjeen commented on a change in pull request #759:
URL: https://github.com/apache/cassandra/pull/759#discussion_r504803812
##########
File path: src/java/org/apache/cassandra/gms/Gossiper.java
##########
@@ -777,23 +787,42 @@ public int getCurrentGenerationNumber(InetAddressAndPort endpoint)
return endpointStateMap.get(endpoint).getHeartBeatState().getGeneration();
}
+ private boolean sendGossip(Message<GossipDigestSyn> message, Set<InetAddressAndPort> epSet)
+ {
+ return sendGossip(message, epSet, null);
+ }
+
/**
* Returns true if the chosen target was also a seed. False otherwise
*
* @param message
* @param epSet a set of endpoint from which a random endpoint is chosen.
+ * @param filter whether or not we should attempt to gossip to this node in the first place
* @return true if the chosen endpoint is also a seed.
*/
- private boolean sendGossip(Message<GossipDigestSyn> message, Set<InetAddressAndPort> epSet)
+ private boolean sendGossip(Message<GossipDigestSyn> message, Set<InetAddressAndPort> epSet, Predicate<InetAddressAndPort> filter)
Review comment:
Implemented suggestioin in in a patch that actually deals with this; here we only need a temporary remedy.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
[GitHub] [cassandra] ifesdjeen commented on a change in pull request #759: Improve machinery for testing bootstrap and range movements
Posted by GitBox <gi...@apache.org>.
ifesdjeen commented on a change in pull request #759:
URL: https://github.com/apache/cassandra/pull/759#discussion_r504543036
##########
File path: test/distributed/org/apache/cassandra/distributed/action/GossipHelper.java
##########
@@ -0,0 +1,464 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.distributed.action;
+
+
+import java.io.IOException;
+import java.net.InetSocketAddress;
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.TimeUnit;
+import java.util.function.Predicate;
+import java.util.stream.Stream;
+
+import net.openhft.chronicle.core.util.SerializableBiFunction;
+import net.openhft.chronicle.core.util.SerializableConsumer;
+import org.apache.cassandra.db.SystemKeyspace;
+import org.apache.cassandra.dht.IPartitioner;
+import org.apache.cassandra.dht.Token;
+import org.apache.cassandra.distributed.api.ICluster;
+import org.apache.cassandra.distributed.api.IInstance;
+import org.apache.cassandra.distributed.api.IInvokableInstance;
+import org.apache.cassandra.distributed.api.IIsolatedExecutor;
+import org.apache.cassandra.distributed.impl.Instance;
+import org.apache.cassandra.distributed.shared.VersionedApplicationState;
+import org.apache.cassandra.gms.ApplicationState;
+import org.apache.cassandra.gms.EndpointState;
+import org.apache.cassandra.gms.Gossiper;
+import org.apache.cassandra.gms.VersionedValue;
+import org.apache.cassandra.io.util.DataInputBuffer;
+import org.apache.cassandra.io.util.DataOutputBuffer;
+import org.apache.cassandra.locator.InetAddressAndPort;
+import org.apache.cassandra.locator.TokenMetadata;
+import org.apache.cassandra.net.MessagingService;
+import org.apache.cassandra.schema.MigrationManager;
+import org.apache.cassandra.service.PendingRangeCalculatorService;
+import org.apache.cassandra.service.StorageService;
+import org.apache.cassandra.utils.FBUtilities;
+
+import static org.apache.cassandra.distributed.impl.DistributedTestSnitch.toCassandraInetAddressAndPort;
+
+
+public class GossipHelper
+{
+
+ public static ClusterAction clusterAction(InstanceAction action)
Review comment:
> the current InstancAction has cluster as the first argument
`InstanceAction` doesn't have cluster as a first argument, it's just a consumer over invokable.
> Serializable goes away in the patch
I did remove `Serializable` from `InstanceAction`, too. It wasn't strictly required here either, but did made things like capturing multiple variables more convenient.
> we hard code the interface rather than relying on what the cluster provides
We do not hardcode anything, we're using `run(Consumer<I> action)` same as `foreach` does.
To address a more general point,
> in your examples there are no real differences between run and forEach, so I rather have forEach only.
There are differences:
1. `Action` is an atomic unit of logic, unlike a static method. You can immediately see all things related to a specific action, reuse, and move then at your discression. Using static methods will quickly get out of hand when we have more sophisticated actions.
2. Separation of input arguments (for example "disseminate gossip state of the node X") and `target`, making `target` explicit and common for all cases.
3. Main idea behind the `Action` was to create reusable pieces of logic you can apply to cluster or nodes. For now, logic is simple, like "pull schema fom X, and then bootstrap", but we can reuse similar sequences of steps in:
a. Harry, where we can schedule different actions against different sets of nodes, producing reliable results
b. In upgrade test, where you'll be able to run named actions aginst instances despite the fact they have different versions.
To do (a) and (b) with static methods, we'll have to _still_ implement some interface.
4. Finally, this is useful things like chaining actions:
```
cluster.run(asList(pullSchemaFrom(cluster.get(1)),
bootstrap()),
newInstance.config().num());
```
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
[GitHub] [cassandra] dcapwell commented on a change in pull request #759: Improve machinery for testing bootstrap and range movements
Posted by GitBox <gi...@apache.org>.
dcapwell commented on a change in pull request #759:
URL: https://github.com/apache/cassandra/pull/759#discussion_r508763388
##########
File path: test/distributed/org/apache/cassandra/distributed/action/GossipHelper.java
##########
@@ -0,0 +1,431 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.distributed.action;
+
+import java.io.IOException;
+import java.io.Serializable;
+import java.net.InetSocketAddress;
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.TimeUnit;
+import java.util.stream.Stream;
+
+import net.openhft.chronicle.core.util.SerializableBiFunction;
+import org.apache.cassandra.db.SystemKeyspace;
+import org.apache.cassandra.dht.IPartitioner;
+import org.apache.cassandra.dht.Token;
+import org.apache.cassandra.distributed.api.IInstance;
+import org.apache.cassandra.distributed.api.IInvokableInstance;
+import org.apache.cassandra.distributed.api.IIsolatedExecutor;
+import org.apache.cassandra.distributed.impl.Instance;
+import org.apache.cassandra.distributed.shared.VersionedApplicationState;
+import org.apache.cassandra.gms.ApplicationState;
+import org.apache.cassandra.gms.EndpointState;
+import org.apache.cassandra.gms.Gossiper;
+import org.apache.cassandra.gms.VersionedValue;
+import org.apache.cassandra.io.util.DataInputBuffer;
+import org.apache.cassandra.io.util.DataOutputBuffer;
+import org.apache.cassandra.locator.InetAddressAndPort;
+import org.apache.cassandra.locator.TokenMetadata;
+import org.apache.cassandra.net.MessagingService;
+import org.apache.cassandra.schema.MigrationManager;
+import org.apache.cassandra.service.PendingRangeCalculatorService;
+import org.apache.cassandra.service.StorageService;
+import org.apache.cassandra.utils.FBUtilities;
+
+import static org.apache.cassandra.distributed.impl.DistributedTestSnitch.toCassandraInetAddressAndPort;
+
+public class GossipHelper
+{
+ public static InstanceAction statusToBootstrap(IInvokableInstance newNode)
+ {
+ return (instance) ->
+ {
+ changeGossipState(instance,
+ newNode,
+ Arrays.asList(tokens(newNode),
+ statusBootstrapping(newNode),
+ statusWithPortBootstrapping(newNode)));
+ };
+ }
+
+ public static InstanceAction statusToNormal(IInvokableInstance peer)
+ {
+ return (target) ->
+ {
+ changeGossipState(target,
+ peer,
+ Arrays.asList(tokens(peer),
+ statusNormal(peer),
+ releaseVersion(peer),
+ statusWithPortNormal(peer)));
+ };
+ }
+
+ /**
+ * This method is unsafe and should be used _only_ when gossip is not used or available: it creates versioned values on the
+ * target instance, which means Gossip versioning gets out of sync. Use a safe couterpart at all times when performing _any_
+ * ring movement operations _or_ if Gossip is used.
+ */
+ public static InstanceAction unsafeStatusToNormal(IInstance peer)
+ {
+ return (target) ->
+ {
+ changeGossipState(target,
+ peer,
+ Arrays.asList(unsafeVersionedToken(target,
+ ApplicationState.TOKENS,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).tokens(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeVersionedToken(target,
+ ApplicationState.STATUS,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeVersionedToken(target,
+ ApplicationState.STATUS_WITH_PORT,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeReleaseVersion(target,
+ peer.config().getString("partitioner"),
+ peer.getReleaseVersionString())));
+ };
+ }
+
+ public static InstanceAction statusToLeaving(IInvokableInstance newNode)
+ {
+ return (instance) -> {
+ changeGossipState(instance,
+ newNode,
+ Arrays.asList(tokens(newNode),
+ statusLeaving(newNode),
+ statusWithPortLeaving(newNode)));
+ };
+ }
+
+ public static InstanceAction bootstrap()
+ {
+ return new BootstrapAction();
+ }
+
+ public static InstanceAction bootstrap(boolean joinRing, Duration waitForBootstrap, Duration waitForSchema)
+ {
+ return new BootstrapAction(joinRing, waitForBootstrap, waitForSchema);
+ }
+
+ public static InstanceAction disseminateGossipState(IInvokableInstance newNode)
+ {
+ return new DisseminateGossipState(newNode);
+ }
+
+ public static InstanceAction pullSchemaFrom(IInvokableInstance pullFrom)
+ {
+ return new PullSchemaFrom(pullFrom);
+ }
+
+ private static InstanceAction disableBinary()
+ {
+ return (instance) -> {
+ instance.runOnInstance(StorageService.instance::stopNativeTransport);
+ };
+ }
+
+ private static class DisseminateGossipState implements InstanceAction
+ {
+ final Map<InetSocketAddress, byte[]> gossipState;
+
+ public DisseminateGossipState(IInvokableInstance... from)
+ {
+ gossipState = new HashMap<>();
+ for (IInvokableInstance node : from)
+ {
+ byte[] epBytes = node.callsOnInstance(() -> {
+ EndpointState epState = Gossiper.instance.getEndpointStateForEndpoint(FBUtilities.getBroadcastAddressAndPort());
+ return toBytes(epState);
+ }).call();
+ gossipState.put(node.broadcastAddress(), epBytes);
+ }
+ }
+
+ public void accept(IInvokableInstance instance)
+ {
+ instance.appliesOnInstance((IIsolatedExecutor.SerializableFunction<Map<InetSocketAddress, byte[]>, Void>)
+ (map) -> {
+ Map<InetAddressAndPort, EndpointState> newState = new HashMap<>();
+ for (Map.Entry<InetSocketAddress, byte[]> e : map.entrySet())
+ newState.put(toCassandraInetAddressAndPort(e.getKey()), fromBytes(e.getValue()));
+
+ Gossiper.runInGossipStageBlocking(() -> {
+ Gossiper.instance.applyStateLocally(newState);
+ });
+ return null;
+ }).apply(gossipState);
+ }
+ }
+
+ public static byte[] toBytes(EndpointState epState)
+ {
+ try (DataOutputBuffer out = new DataOutputBuffer(1024))
+ {
+ EndpointState.serializer.serialize(epState, out, MessagingService.current_version);
+ return out.toByteArray();
+ }
+ catch (IOException e)
+ {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public static EndpointState fromBytes(byte[] bytes)
+ {
+ try (DataInputBuffer in = new DataInputBuffer(bytes))
+ {
+ return EndpointState.serializer.deserialize(in, MessagingService.current_version);
+ }
+ catch (Throwable t)
+ {
+ throw new RuntimeException(t);
+ }
+ }
+
+ private static class PullSchemaFrom implements InstanceAction
+ {
+ final InetSocketAddress pullFrom;
+
+ public PullSchemaFrom(IInvokableInstance pullFrom)
+ {
+ this.pullFrom = pullFrom.broadcastAddress();;
+ }
+
+ public void accept(IInvokableInstance pullTo)
+ {
+ pullTo.acceptsOnInstance((InetSocketAddress pullFrom) -> {
+ InetAddressAndPort endpoint = toCassandraInetAddressAndPort(pullFrom);
+ EndpointState state = Gossiper.instance.getEndpointStateForEndpoint(endpoint);
+ MigrationManager.scheduleSchemaPull(endpoint, state);
+ MigrationManager.waitUntilReadyForBootstrap();
+ }).accept(pullFrom);
+ }
+ }
+
+ private static class BootstrapAction implements InstanceAction, Serializable
+ {
+ private final boolean joinRing;
+ private final Duration waitForBootstrap;
+ private final Duration waitForSchema;
+
+ public BootstrapAction()
+ {
+ this(true, Duration.ofMinutes(10), Duration.ofSeconds(10));
+ }
+
+ public BootstrapAction(boolean joinRing, Duration waitForBootstrap, Duration waitForSchema)
+ {
+ this.joinRing = joinRing;
+ this.waitForBootstrap = waitForBootstrap;
+ this.waitForSchema = waitForSchema;
+ }
+
+ public void accept(IInvokableInstance instance)
+ {
+ instance.appliesOnInstance((String partitionerString, String tokenString) -> {
+ IPartitioner partitioner = FBUtilities.newPartitioner(partitionerString);
+ List<Token> tokens = Collections.singletonList(partitioner.getTokenFactory().fromString(tokenString));
+ try
+ {
+ SystemKeyspace.setBootstrapState(SystemKeyspace.BootstrapState.IN_PROGRESS);
+ StorageService.instance.waitForSchema((int) waitForSchema.toMillis());
+ PendingRangeCalculatorService.instance.blockUntilFinished();
+ StorageService.instance.startBootstrap(tokens).get(waitForBootstrap.toMillis(), TimeUnit.MILLISECONDS);
+ StorageService.instance.setUpDistributedSystemKeyspaces();
+ if (joinRing)
+ StorageService.instance.finishJoiningRing(true, tokens);
+ }
+ catch (Throwable t)
+ {
+ throw new RuntimeException(t);
+ }
+
+ return null;
+ }).apply(instance.config().getString("partitioner"), instance.config().getString("initial_token"));
+ }
+ }
+
+ public static InstanceAction decomission()
+ {
+ return (target) -> {
+ target.runOnInstance(() -> {
+ try
+ {
+ StorageService.instance.decommission(false);
+ }
+ catch (InterruptedException e)
+ {
+ throw new RuntimeException();
+ }
+ });
+ };
+ }
+
+
+ public static VersionedApplicationState tokens(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.TOKENS, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).tokens(tokens));
+ }
+
+ public static VersionedApplicationState unsafeReleaseVersion(IInvokableInstance instance, String partitionerStr, String releaseVersionStr)
+ {
+ return instance.appliesOnInstance((String partitionerString, String releaseVersion) -> {
+ IPartitioner partitioner = FBUtilities.newPartitioner(partitionerString);
+ VersionedValue versionedValue = new VersionedValue.VersionedValueFactory(partitioner).releaseVersion(releaseVersion);
+ return new VersionedApplicationState(ApplicationState.RELEASE_VERSION.ordinal(), versionedValue.value, versionedValue.version);
+ }).apply(partitionerStr, releaseVersionStr);
+ }
+
+ public static VersionedApplicationState releaseVersion(IInvokableInstance instance)
+ {
+ return unsafeReleaseVersion(instance, instance.config().getString("partitioner"), instance.getReleaseVersionString());
+ }
+
+ public static VersionedApplicationState statusNormal(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens));
+ }
+
+ public static VersionedApplicationState statusWithPortNormal(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS_WITH_PORT, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens));
+ }
+
+ public static VersionedApplicationState statusBootstrapping(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).bootstrapping(tokens));
+ }
+
+ public static VersionedApplicationState statusWithPortBootstrapping(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS_WITH_PORT, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).bootstrapping(tokens));
+ }
+
+ public static VersionedApplicationState statusLeaving(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).leaving(tokens));
+ }
+
+ public static VersionedApplicationState statusWithPortLeaving(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS_WITH_PORT, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).leaving(tokens));
+ }
+
+ public static VersionedValue toVersionedValue(VersionedApplicationState vv)
+ {
+ return VersionedValue.unsafeMakeVersionedValue(vv.value, vv.version);
+ }
+
+ public static ApplicationState toApplicationState(VersionedApplicationState vv)
+ {
+ return ApplicationState.values()[vv.applicationState];
+ }
+
+ public static VersionedApplicationState unsafeVersionedToken(IInvokableInstance instance,
+ ApplicationState applicationState,
+ SerializableBiFunction<IPartitioner, Collection<Token>, VersionedValue> supplier,
+ String partitionerStr, String initialTokenStr)
+ {
+ return instance.appliesOnInstance((String partitionerString, String tokenString) -> {
+ IPartitioner partitioner = FBUtilities.newPartitioner(partitionerString);
+ Token token = partitioner.getTokenFactory().fromString(tokenString);
+
+ VersionedValue versionedValue = supplier.apply(partitioner, Collections.singleton(token));
+ return new VersionedApplicationState(applicationState.ordinal(), versionedValue.value, versionedValue.version);
+ }).apply(partitionerStr, initialTokenStr);
+ }
+
+ public static VersionedApplicationState versionedToken(IInvokableInstance instance, ApplicationState applicationState, SerializableBiFunction<IPartitioner, Collection<Token>, VersionedValue> supplier)
+ {
+ return unsafeVersionedToken(instance, applicationState, supplier, instance.config().getString("partitioner"), instance.config().getString("initial_token"));
+ }
+
+ public void removeFromRing(IInstance peer)
+ {
+ InetAddressAndPort endpoint = toCassandraInetAddressAndPort(peer.broadcastAddress());
+
+ TokenMetadata tokenMetadata = StorageService.instance.getTokenMetadata();
+ tokenMetadata.removeEndpoint(endpoint);
+ Collection<Token> tokens = tokenMetadata.getTokens(endpoint);
+ if (!tokens.isEmpty())
+ tokenMetadata.removeBootstrapTokens(tokens);
+
+ Gossiper.runInGossipStageBlocking(() -> Gossiper.instance.unsafeAnulEndpoint(endpoint));
+
+ SystemKeyspace.removeEndpoint(endpoint);
+ PendingRangeCalculatorService.instance.update();
+ PendingRangeCalculatorService.instance.blockUntilFinished();
+ }
+
+ public static void changeGossipState(Stream<IInvokableInstance> targets, Instance peer, List<VersionedApplicationState> newState)
+ {
+ targets.forEach((instance) -> {
+ changeGossipState(instance, peer, newState);
+ });
+ }
+
+ /**
+ * Changes gossip state of the `peer` on `target`
+ */
+ public static void changeGossipState(IInvokableInstance target, IInstance peer, List<VersionedApplicationState> newState)
+ {
+ int version = peer.isShutdown() ? MessagingService.current_version : peer.getMessagingVersion();
+
+ target.appliesOnInstance((InetSocketAddress addr, UUID hostId, Integer messagingVersion) -> {
+ InetAddressAndPort endpoint = toCassandraInetAddressAndPort(addr);
+ StorageService storageService = StorageService.instance;
+
+ Gossiper.runInGossipStageBlocking(() -> {
+ EndpointState state = Gossiper.instance.getEndpointStateForEndpoint(endpoint);
+ if (state == null)
+ {
+ Gossiper.instance.initializeNodeUnsafe(endpoint, hostId, 1);
Review comment:
the change was to add it based off the peer state, but if its replaced; cool.
+1
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
[GitHub] [cassandra] dcapwell commented on a change in pull request #759: Improve machinery for testing bootstrap and range movements
Posted by GitBox <gi...@apache.org>.
dcapwell commented on a change in pull request #759:
URL: https://github.com/apache/cassandra/pull/759#discussion_r508718910
##########
File path: test/distributed/org/apache/cassandra/distributed/action/GossipHelper.java
##########
@@ -0,0 +1,431 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.distributed.action;
+
+import java.io.IOException;
+import java.io.Serializable;
+import java.net.InetSocketAddress;
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.TimeUnit;
+import java.util.stream.Stream;
+
+import net.openhft.chronicle.core.util.SerializableBiFunction;
+import org.apache.cassandra.db.SystemKeyspace;
+import org.apache.cassandra.dht.IPartitioner;
+import org.apache.cassandra.dht.Token;
+import org.apache.cassandra.distributed.api.IInstance;
+import org.apache.cassandra.distributed.api.IInvokableInstance;
+import org.apache.cassandra.distributed.api.IIsolatedExecutor;
+import org.apache.cassandra.distributed.impl.Instance;
+import org.apache.cassandra.distributed.shared.VersionedApplicationState;
+import org.apache.cassandra.gms.ApplicationState;
+import org.apache.cassandra.gms.EndpointState;
+import org.apache.cassandra.gms.Gossiper;
+import org.apache.cassandra.gms.VersionedValue;
+import org.apache.cassandra.io.util.DataInputBuffer;
+import org.apache.cassandra.io.util.DataOutputBuffer;
+import org.apache.cassandra.locator.InetAddressAndPort;
+import org.apache.cassandra.locator.TokenMetadata;
+import org.apache.cassandra.net.MessagingService;
+import org.apache.cassandra.schema.MigrationManager;
+import org.apache.cassandra.service.PendingRangeCalculatorService;
+import org.apache.cassandra.service.StorageService;
+import org.apache.cassandra.utils.FBUtilities;
+
+import static org.apache.cassandra.distributed.impl.DistributedTestSnitch.toCassandraInetAddressAndPort;
+
+public class GossipHelper
+{
+ public static InstanceAction statusToBootstrap(IInvokableInstance newNode)
+ {
+ return (instance) ->
+ {
+ changeGossipState(instance,
+ newNode,
+ Arrays.asList(tokens(newNode),
+ statusBootstrapping(newNode),
+ statusWithPortBootstrapping(newNode)));
+ };
+ }
+
+ public static InstanceAction statusToNormal(IInvokableInstance peer)
+ {
+ return (target) ->
+ {
+ changeGossipState(target,
+ peer,
+ Arrays.asList(tokens(peer),
+ statusNormal(peer),
+ releaseVersion(peer),
+ statusWithPortNormal(peer)));
+ };
+ }
+
+ /**
+ * This method is unsafe and should be used _only_ when gossip is not used or available: it creates versioned values on the
+ * target instance, which means Gossip versioning gets out of sync. Use a safe couterpart at all times when performing _any_
+ * ring movement operations _or_ if Gossip is used.
+ */
+ public static InstanceAction unsafeStatusToNormal(IInstance peer)
+ {
+ return (target) ->
+ {
+ changeGossipState(target,
+ peer,
+ Arrays.asList(unsafeVersionedToken(target,
+ ApplicationState.TOKENS,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).tokens(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeVersionedToken(target,
+ ApplicationState.STATUS,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeVersionedToken(target,
+ ApplicationState.STATUS_WITH_PORT,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeReleaseVersion(target,
+ peer.config().getString("partitioner"),
+ peer.getReleaseVersionString())));
+ };
+ }
+
+ public static InstanceAction statusToLeaving(IInvokableInstance newNode)
+ {
+ return (instance) -> {
+ changeGossipState(instance,
+ newNode,
+ Arrays.asList(tokens(newNode),
+ statusLeaving(newNode),
+ statusWithPortLeaving(newNode)));
+ };
+ }
+
+ public static InstanceAction bootstrap()
+ {
+ return new BootstrapAction();
+ }
+
+ public static InstanceAction bootstrap(boolean joinRing, Duration waitForBootstrap, Duration waitForSchema)
+ {
+ return new BootstrapAction(joinRing, waitForBootstrap, waitForSchema);
+ }
+
+ public static InstanceAction disseminateGossipState(IInvokableInstance newNode)
+ {
+ return new DisseminateGossipState(newNode);
+ }
+
+ public static InstanceAction pullSchemaFrom(IInvokableInstance pullFrom)
+ {
+ return new PullSchemaFrom(pullFrom);
+ }
+
+ private static InstanceAction disableBinary()
+ {
+ return (instance) -> {
+ instance.runOnInstance(StorageService.instance::stopNativeTransport);
+ };
+ }
+
+ private static class DisseminateGossipState implements InstanceAction
+ {
+ final Map<InetSocketAddress, byte[]> gossipState;
+
+ public DisseminateGossipState(IInvokableInstance... from)
+ {
+ gossipState = new HashMap<>();
+ for (IInvokableInstance node : from)
+ {
+ byte[] epBytes = node.callsOnInstance(() -> {
+ EndpointState epState = Gossiper.instance.getEndpointStateForEndpoint(FBUtilities.getBroadcastAddressAndPort());
+ return toBytes(epState);
+ }).call();
+ gossipState.put(node.broadcastAddress(), epBytes);
+ }
+ }
+
+ public void accept(IInvokableInstance instance)
+ {
+ instance.appliesOnInstance((IIsolatedExecutor.SerializableFunction<Map<InetSocketAddress, byte[]>, Void>)
+ (map) -> {
+ Map<InetAddressAndPort, EndpointState> newState = new HashMap<>();
+ for (Map.Entry<InetSocketAddress, byte[]> e : map.entrySet())
+ newState.put(toCassandraInetAddressAndPort(e.getKey()), fromBytes(e.getValue()));
+
+ Gossiper.runInGossipStageBlocking(() -> {
+ Gossiper.instance.applyStateLocally(newState);
+ });
+ return null;
+ }).apply(gossipState);
+ }
+ }
+
+ public static byte[] toBytes(EndpointState epState)
+ {
+ try (DataOutputBuffer out = new DataOutputBuffer(1024))
+ {
+ EndpointState.serializer.serialize(epState, out, MessagingService.current_version);
+ return out.toByteArray();
+ }
+ catch (IOException e)
+ {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public static EndpointState fromBytes(byte[] bytes)
+ {
+ try (DataInputBuffer in = new DataInputBuffer(bytes))
+ {
+ return EndpointState.serializer.deserialize(in, MessagingService.current_version);
+ }
+ catch (Throwable t)
+ {
+ throw new RuntimeException(t);
+ }
+ }
+
+ private static class PullSchemaFrom implements InstanceAction
+ {
+ final InetSocketAddress pullFrom;
+
+ public PullSchemaFrom(IInvokableInstance pullFrom)
+ {
+ this.pullFrom = pullFrom.broadcastAddress();;
+ }
+
+ public void accept(IInvokableInstance pullTo)
+ {
+ pullTo.acceptsOnInstance((InetSocketAddress pullFrom) -> {
+ InetAddressAndPort endpoint = toCassandraInetAddressAndPort(pullFrom);
+ EndpointState state = Gossiper.instance.getEndpointStateForEndpoint(endpoint);
+ MigrationManager.scheduleSchemaPull(endpoint, state);
+ MigrationManager.waitUntilReadyForBootstrap();
+ }).accept(pullFrom);
+ }
+ }
+
+ private static class BootstrapAction implements InstanceAction, Serializable
+ {
+ private final boolean joinRing;
+ private final Duration waitForBootstrap;
+ private final Duration waitForSchema;
+
+ public BootstrapAction()
+ {
+ this(true, Duration.ofMinutes(10), Duration.ofSeconds(10));
+ }
+
+ public BootstrapAction(boolean joinRing, Duration waitForBootstrap, Duration waitForSchema)
+ {
+ this.joinRing = joinRing;
+ this.waitForBootstrap = waitForBootstrap;
+ this.waitForSchema = waitForSchema;
+ }
+
+ public void accept(IInvokableInstance instance)
+ {
+ instance.appliesOnInstance((String partitionerString, String tokenString) -> {
+ IPartitioner partitioner = FBUtilities.newPartitioner(partitionerString);
+ List<Token> tokens = Collections.singletonList(partitioner.getTokenFactory().fromString(tokenString));
+ try
+ {
+ SystemKeyspace.setBootstrapState(SystemKeyspace.BootstrapState.IN_PROGRESS);
+ StorageService.instance.waitForSchema((int) waitForSchema.toMillis());
Review comment:
separate works for me.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
[GitHub] [cassandra] ifesdjeen commented on a change in pull request #759: Improve machinery for testing bootstrap and range movements
Posted by GitBox <gi...@apache.org>.
ifesdjeen commented on a change in pull request #759:
URL: https://github.com/apache/cassandra/pull/759#discussion_r507830934
##########
File path: test/distributed/org/apache/cassandra/distributed/impl/AbstractCluster.java
##########
@@ -448,6 +444,33 @@ public int size()
i.config().localRack().equals(rackName));
}
+ public void run(Consumer<? super I> action, Predicate<I> filter) {
+ run(Collections.singletonList(action), filter);
+ }
+
+ public void run(Collection<Consumer<? super I>> actions, Predicate<I> filter) {
Review comment:
👍
##########
File path: test/distributed/org/apache/cassandra/distributed/impl/AbstractCluster.java
##########
@@ -448,6 +444,33 @@ public int size()
i.config().localRack().equals(rackName));
}
+ public void run(Consumer<? super I> action, Predicate<I> filter) {
+ run(Collections.singletonList(action), filter);
+ }
+
+ public void run(Collection<Consumer<? super I>> actions, Predicate<I> filter) {
+ stream().forEach(instance -> {
+ for (Consumer<? super I> action : actions)
+ {
+ if (filter.test(instance))
+ action.accept(instance);
+ }
+
+ });
+ }
+
+ public void run(Consumer<? super I> action, int... instanceIds) {
Review comment:
👍
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
[GitHub] [cassandra] dcapwell commented on a change in pull request #759: Improve machinery for testing bootstrap and range movements
Posted by GitBox <gi...@apache.org>.
dcapwell commented on a change in pull request #759:
URL: https://github.com/apache/cassandra/pull/759#discussion_r508774962
##########
File path: test/distributed/org/apache/cassandra/distributed/impl/Instance.java
##########
@@ -467,17 +465,23 @@ public void startup(ICluster cluster)
StorageService.instance.registerDaemon(CassandraDaemon.getInstanceForTesting());
if (config.has(GOSSIP))
{
+ MigrationManager.setUptimeFn(() -> TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startedAt));
StorageService.instance.initServer();
StorageService.instance.removeShutdownHook();
Gossiper.waitToSettle();
}
else
{
- initializeRing(cluster);
+ cluster.stream().forEach(peer -> {
+ if (peer instanceof IInvokableInstance)
+ GossipHelper.statusToNormal((IInvokableInstance) peer).accept(this);
+ else
+ GossipHelper.unsafeStatusToNormal((IInstance) peer).accept(this);
Review comment:
spoke in slack about this, the reason is UpgradeCluster
```
public interface IUpgradeableInstance extends IInstance {
void setVersion(Version var1);
}
```
We use IInstance there so need the special case
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
[GitHub] [cassandra] ifesdjeen commented on a change in pull request #759: Improve machinery for testing bootstrap and range movements
Posted by GitBox <gi...@apache.org>.
ifesdjeen commented on a change in pull request #759:
URL: https://github.com/apache/cassandra/pull/759#discussion_r504573698
##########
File path: test/distributed/org/apache/cassandra/distributed/impl/AbstractCluster.java
##########
@@ -448,6 +443,22 @@ public int size()
i.config().localRack().equals(rackName));
}
+ public void run(Consumer<I> action) {
Review comment:
removed this one
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
[GitHub] [cassandra] emersonrocha85 commented on pull request #759: Improve machinery for testing bootstrap and range movements
Posted by GitBox <gi...@apache.org>.
emersonrocha85 commented on pull request #759:
URL: https://github.com/apache/cassandra/pull/759#issuecomment-712218526
Thanks
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
[GitHub] [cassandra] dcapwell commented on a change in pull request #759: Improve machinery for testing bootstrap and range movements
Posted by GitBox <gi...@apache.org>.
dcapwell commented on a change in pull request #759:
URL: https://github.com/apache/cassandra/pull/759#discussion_r505701927
##########
File path: test/distributed/org/apache/cassandra/distributed/test/BootstrapTest.java
##########
@@ -18,85 +18,244 @@
package org.apache.cassandra.distributed.test;
+import java.net.InetSocketAddress;
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.HashSet;
import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.locks.LockSupport;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.junit.Assert;
import org.junit.Test;
+import com.datastax.driver.core.ResultSet;
+import com.datastax.driver.core.Session;
+import com.datastax.driver.core.SimpleStatement;
+import com.datastax.driver.core.Statement;
+import com.datastax.driver.core.policies.RoundRobinPolicy;
+import org.apache.cassandra.dht.Range;
+import org.apache.cassandra.dht.Token;
import org.apache.cassandra.distributed.Cluster;
import org.apache.cassandra.distributed.api.ConsistencyLevel;
import org.apache.cassandra.distributed.api.ICluster;
import org.apache.cassandra.distributed.api.IInstanceConfig;
+import org.apache.cassandra.distributed.api.IInvokableInstance;
import org.apache.cassandra.distributed.api.TokenSupplier;
+import org.apache.cassandra.distributed.impl.DistributedTestSnitch;
+import org.apache.cassandra.distributed.impl.RowUtil;
import org.apache.cassandra.distributed.shared.NetworkTopology;
+import org.apache.cassandra.locator.EndpointsForRange;
+import org.apache.cassandra.locator.InetAddressAndPort;
+import org.apache.cassandra.service.StorageService;
+import static java.util.Arrays.*;
+import static org.apache.cassandra.distributed.action.GossipHelper.bootstrap;
+import static org.apache.cassandra.distributed.action.GossipHelper.decomission;
+import static org.apache.cassandra.distributed.action.GossipHelper.disseminateGossipState;
+import static org.apache.cassandra.distributed.action.GossipHelper.pullSchemaFrom;
+import static org.apache.cassandra.distributed.action.GossipHelper.statusToBootstrap;
import static org.apache.cassandra.distributed.api.Feature.GOSSIP;
+import static org.apache.cassandra.distributed.api.Feature.NATIVE_PROTOCOL;
import static org.apache.cassandra.distributed.api.Feature.NETWORK;
+import static org.apache.cassandra.distributed.shared.AssertUtils.assertRows;
+import static org.apache.cassandra.distributed.shared.AssertUtils.row;
-// TODO: this test should be removed after running in-jvm dtests is set up via the shared API repository
public class BootstrapTest extends TestBaseImpl
{
-
@Test
public void bootstrapTest() throws Throwable
{
int originalNodeCount = 2;
int expandedNodeCount = originalNodeCount + 1;
- Cluster.Builder builder = builder().withNodes(originalNodeCount)
- .withTokenSupplier(TokenSupplier.evenlyDistributedTokens(expandedNodeCount))
- .withNodeIdTopology(NetworkTopology.singleDcNetworkTopology(expandedNodeCount, "dc0", "rack0"))
- .withConfig(config -> config.with(NETWORK, GOSSIP));
-
- Map<Integer, Long> withBootstrap = null;
- Map<Integer, Long> naturally = null;
- try (Cluster cluster = builder.withNodes(originalNodeCount).start())
+
+ try (Cluster cluster = builder().withNodes(originalNodeCount)
+ .withTokenSupplier(TokenSupplier.evenlyDistributedTokens(expandedNodeCount))
+ .withNodeIdTopology(NetworkTopology.singleDcNetworkTopology(expandedNodeCount, "dc0", "rack0"))
+ .withConfig(config -> config.with(NETWORK, GOSSIP))
+ .start())
{
- populate(cluster);
+ populate(cluster,0, 100);
IInstanceConfig config = cluster.newInstanceConfig();
- config.set("auto_bootstrap", true);
-
- cluster.bootstrap(config).startup();
+ IInvokableInstance newInstance = cluster.initialize(config);
+ withJoinRing(false, () -> newInstance.startup(cluster));
- cluster.stream().forEach(instance -> {
- instance.nodetool("cleanup", KEYSPACE, "tbl");
- });
+ cluster.forEach(statusToBootstrap(newInstance));
+ cluster.run(asList(pullSchemaFrom(cluster.get(1)),
Review comment:
> I've added the test you've implemented as autoBootstrapTest.
Works for me, fine with both versions.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
[GitHub] [cassandra] iamaleksey commented on a change in pull request #759: Improve machinery for testing bootstrap and range movements
Posted by GitBox <gi...@apache.org>.
iamaleksey commented on a change in pull request #759:
URL: https://github.com/apache/cassandra/pull/759#discussion_r507722441
##########
File path: test/distributed/org/apache/cassandra/distributed/impl/Instance.java
##########
@@ -443,25 +457,31 @@ public void startup(ICluster cluster)
StorageService.instance.registerDaemon(CassandraDaemon.getInstanceForTesting());
if (config.has(GOSSIP))
{
+ MigrationManager.setUptimeFn(() -> System.currentTimeMillis() - startedAt);
Review comment:
Doesn't really matter in this instance, but I too would prefer use of `nanoTime()` here, if only to set a more idiomatic example to whoever might be looking at this code.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
[GitHub] [cassandra] ifesdjeen commented on a change in pull request #759: Improve machinery for testing bootstrap and range movements
Posted by GitBox <gi...@apache.org>.
ifesdjeen commented on a change in pull request #759:
URL: https://github.com/apache/cassandra/pull/759#discussion_r508773210
##########
File path: test/distributed/org/apache/cassandra/distributed/action/GossipHelper.java
##########
@@ -0,0 +1,431 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.distributed.action;
+
+import java.io.IOException;
+import java.io.Serializable;
+import java.net.InetSocketAddress;
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.TimeUnit;
+import java.util.stream.Stream;
+
+import net.openhft.chronicle.core.util.SerializableBiFunction;
+import org.apache.cassandra.db.SystemKeyspace;
+import org.apache.cassandra.dht.IPartitioner;
+import org.apache.cassandra.dht.Token;
+import org.apache.cassandra.distributed.api.IInstance;
+import org.apache.cassandra.distributed.api.IInvokableInstance;
+import org.apache.cassandra.distributed.api.IIsolatedExecutor;
+import org.apache.cassandra.distributed.impl.Instance;
+import org.apache.cassandra.distributed.shared.VersionedApplicationState;
+import org.apache.cassandra.gms.ApplicationState;
+import org.apache.cassandra.gms.EndpointState;
+import org.apache.cassandra.gms.Gossiper;
+import org.apache.cassandra.gms.VersionedValue;
+import org.apache.cassandra.io.util.DataInputBuffer;
+import org.apache.cassandra.io.util.DataOutputBuffer;
+import org.apache.cassandra.locator.InetAddressAndPort;
+import org.apache.cassandra.locator.TokenMetadata;
+import org.apache.cassandra.net.MessagingService;
+import org.apache.cassandra.schema.MigrationManager;
+import org.apache.cassandra.service.PendingRangeCalculatorService;
+import org.apache.cassandra.service.StorageService;
+import org.apache.cassandra.utils.FBUtilities;
+
+import static org.apache.cassandra.distributed.impl.DistributedTestSnitch.toCassandraInetAddressAndPort;
+
+public class GossipHelper
+{
+ public static InstanceAction statusToBootstrap(IInvokableInstance newNode)
+ {
+ return (instance) ->
+ {
+ changeGossipState(instance,
+ newNode,
+ Arrays.asList(tokens(newNode),
+ statusBootstrapping(newNode),
+ statusWithPortBootstrapping(newNode)));
+ };
+ }
+
+ public static InstanceAction statusToNormal(IInvokableInstance peer)
+ {
+ return (target) ->
+ {
+ changeGossipState(target,
+ peer,
+ Arrays.asList(tokens(peer),
+ statusNormal(peer),
+ releaseVersion(peer),
+ statusWithPortNormal(peer)));
+ };
+ }
+
+ /**
+ * This method is unsafe and should be used _only_ when gossip is not used or available: it creates versioned values on the
+ * target instance, which means Gossip versioning gets out of sync. Use a safe couterpart at all times when performing _any_
+ * ring movement operations _or_ if Gossip is used.
+ */
+ public static InstanceAction unsafeStatusToNormal(IInstance peer)
+ {
+ return (target) ->
+ {
+ changeGossipState(target,
+ peer,
+ Arrays.asList(unsafeVersionedToken(target,
+ ApplicationState.TOKENS,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).tokens(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeVersionedToken(target,
+ ApplicationState.STATUS,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeVersionedToken(target,
+ ApplicationState.STATUS_WITH_PORT,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeReleaseVersion(target,
+ peer.config().getString("partitioner"),
+ peer.getReleaseVersionString())));
+ };
+ }
+
+ public static InstanceAction statusToLeaving(IInvokableInstance newNode)
+ {
+ return (instance) -> {
+ changeGossipState(instance,
+ newNode,
+ Arrays.asList(tokens(newNode),
+ statusLeaving(newNode),
+ statusWithPortLeaving(newNode)));
+ };
+ }
+
+ public static InstanceAction bootstrap()
+ {
+ return new BootstrapAction();
+ }
+
+ public static InstanceAction bootstrap(boolean joinRing, Duration waitForBootstrap, Duration waitForSchema)
+ {
+ return new BootstrapAction(joinRing, waitForBootstrap, waitForSchema);
+ }
+
+ public static InstanceAction disseminateGossipState(IInvokableInstance newNode)
+ {
+ return new DisseminateGossipState(newNode);
+ }
+
+ public static InstanceAction pullSchemaFrom(IInvokableInstance pullFrom)
+ {
+ return new PullSchemaFrom(pullFrom);
+ }
+
+ private static InstanceAction disableBinary()
+ {
+ return (instance) -> {
+ instance.runOnInstance(StorageService.instance::stopNativeTransport);
+ };
+ }
+
+ private static class DisseminateGossipState implements InstanceAction
+ {
+ final Map<InetSocketAddress, byte[]> gossipState;
+
+ public DisseminateGossipState(IInvokableInstance... from)
+ {
+ gossipState = new HashMap<>();
+ for (IInvokableInstance node : from)
+ {
+ byte[] epBytes = node.callsOnInstance(() -> {
+ EndpointState epState = Gossiper.instance.getEndpointStateForEndpoint(FBUtilities.getBroadcastAddressAndPort());
+ return toBytes(epState);
+ }).call();
+ gossipState.put(node.broadcastAddress(), epBytes);
+ }
+ }
+
+ public void accept(IInvokableInstance instance)
+ {
+ instance.appliesOnInstance((IIsolatedExecutor.SerializableFunction<Map<InetSocketAddress, byte[]>, Void>)
+ (map) -> {
+ Map<InetAddressAndPort, EndpointState> newState = new HashMap<>();
+ for (Map.Entry<InetSocketAddress, byte[]> e : map.entrySet())
+ newState.put(toCassandraInetAddressAndPort(e.getKey()), fromBytes(e.getValue()));
+
+ Gossiper.runInGossipStageBlocking(() -> {
+ Gossiper.instance.applyStateLocally(newState);
+ });
+ return null;
+ }).apply(gossipState);
+ }
+ }
+
+ public static byte[] toBytes(EndpointState epState)
+ {
+ try (DataOutputBuffer out = new DataOutputBuffer(1024))
+ {
+ EndpointState.serializer.serialize(epState, out, MessagingService.current_version);
+ return out.toByteArray();
+ }
+ catch (IOException e)
+ {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public static EndpointState fromBytes(byte[] bytes)
+ {
+ try (DataInputBuffer in = new DataInputBuffer(bytes))
+ {
+ return EndpointState.serializer.deserialize(in, MessagingService.current_version);
+ }
+ catch (Throwable t)
+ {
+ throw new RuntimeException(t);
+ }
+ }
+
+ private static class PullSchemaFrom implements InstanceAction
+ {
+ final InetSocketAddress pullFrom;
+
+ public PullSchemaFrom(IInvokableInstance pullFrom)
+ {
+ this.pullFrom = pullFrom.broadcastAddress();;
+ }
+
+ public void accept(IInvokableInstance pullTo)
+ {
+ pullTo.acceptsOnInstance((InetSocketAddress pullFrom) -> {
+ InetAddressAndPort endpoint = toCassandraInetAddressAndPort(pullFrom);
+ EndpointState state = Gossiper.instance.getEndpointStateForEndpoint(endpoint);
+ MigrationManager.scheduleSchemaPull(endpoint, state);
+ MigrationManager.waitUntilReadyForBootstrap();
+ }).accept(pullFrom);
+ }
+ }
+
+ private static class BootstrapAction implements InstanceAction, Serializable
+ {
+ private final boolean joinRing;
+ private final Duration waitForBootstrap;
+ private final Duration waitForSchema;
+
+ public BootstrapAction()
+ {
+ this(true, Duration.ofMinutes(10), Duration.ofSeconds(10));
+ }
+
+ public BootstrapAction(boolean joinRing, Duration waitForBootstrap, Duration waitForSchema)
+ {
+ this.joinRing = joinRing;
+ this.waitForBootstrap = waitForBootstrap;
+ this.waitForSchema = waitForSchema;
+ }
+
+ public void accept(IInvokableInstance instance)
+ {
+ instance.appliesOnInstance((String partitionerString, String tokenString) -> {
+ IPartitioner partitioner = FBUtilities.newPartitioner(partitionerString);
+ List<Token> tokens = Collections.singletonList(partitioner.getTokenFactory().fromString(tokenString));
+ try
+ {
+ SystemKeyspace.setBootstrapState(SystemKeyspace.BootstrapState.IN_PROGRESS);
+ StorageService.instance.waitForSchema((int) waitForSchema.toMillis());
+ PendingRangeCalculatorService.instance.blockUntilFinished();
+ StorageService.instance.startBootstrap(tokens).get(waitForBootstrap.toMillis(), TimeUnit.MILLISECONDS);
+ StorageService.instance.setUpDistributedSystemKeyspaces();
+ if (joinRing)
+ StorageService.instance.finishJoiningRing(true, tokens);
+ }
+ catch (Throwable t)
+ {
+ throw new RuntimeException(t);
+ }
+
+ return null;
+ }).apply(instance.config().getString("partitioner"), instance.config().getString("initial_token"));
+ }
+ }
+
+ public static InstanceAction decomission()
+ {
+ return (target) -> {
+ target.runOnInstance(() -> {
+ try
+ {
+ StorageService.instance.decommission(false);
Review comment:
👍
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
[GitHub] [cassandra] ifesdjeen commented on a change in pull request #759: Improve machinery for testing bootstrap and range movements
Posted by GitBox <gi...@apache.org>.
ifesdjeen commented on a change in pull request #759:
URL: https://github.com/apache/cassandra/pull/759#discussion_r507709234
##########
File path: src/java/org/apache/cassandra/service/StorageService.java
##########
@@ -622,6 +624,11 @@ public synchronized void initServer() throws ConfigurationException
}
public synchronized void initServer(int delay) throws ConfigurationException
+ {
+ initServer(delay, joinRing);
+ }
+
+ public synchronized void initServer(int delay, boolean joinRing) throws ConfigurationException
Review comment:
Missed this comment somehow. Sure, that makes sense. Removed.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
[GitHub] [cassandra] ifesdjeen commented on a change in pull request #759: Improve machinery for testing bootstrap and range movements
Posted by GitBox <gi...@apache.org>.
ifesdjeen commented on a change in pull request #759:
URL: https://github.com/apache/cassandra/pull/759#discussion_r504804665
##########
File path: src/java/org/apache/cassandra/gms/Gossiper.java
##########
@@ -825,7 +854,7 @@ private void maybeGossipToUnreachableMember(Message<GossipDigestSyn> message)
double prob = unreachableEndpointCount / (liveEndpointCount + 1);
double randDbl = random.nextDouble();
if (randDbl < prob)
- sendGossip(message, unreachableEndpoints.keySet());
+ sendGossip(message, unreachableEndpoints.keySet(), ep -> !isDeadState(getEndpointStateMap().get(ep)));
Review comment:
Since I've implemented this through filiterr, thiis doesn't seem to apply anymore.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
[GitHub] [cassandra] ifesdjeen commented on a change in pull request #759: Improve machinery for testing bootstrap and range movements
Posted by GitBox <gi...@apache.org>.
ifesdjeen commented on a change in pull request #759:
URL: https://github.com/apache/cassandra/pull/759#discussion_r508739935
##########
File path: test/distributed/org/apache/cassandra/distributed/action/GossipHelper.java
##########
@@ -0,0 +1,462 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.distributed.action;
+
+import java.io.IOException;
+import java.io.Serializable;
+import java.net.InetSocketAddress;
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.TimeUnit;
+import java.util.function.Supplier;
+
+import org.apache.cassandra.db.SystemKeyspace;
+import org.apache.cassandra.dht.IPartitioner;
+import org.apache.cassandra.dht.Token;
+import org.apache.cassandra.distributed.api.IInstance;
+import org.apache.cassandra.distributed.api.IInvokableInstance;
+import org.apache.cassandra.distributed.api.IIsolatedExecutor;
+import org.apache.cassandra.distributed.shared.VersionedApplicationState;
+import org.apache.cassandra.gms.ApplicationState;
+import org.apache.cassandra.gms.EndpointState;
+import org.apache.cassandra.gms.Gossiper;
+import org.apache.cassandra.gms.VersionedValue;
+import org.apache.cassandra.io.util.DataInputBuffer;
+import org.apache.cassandra.io.util.DataOutputBuffer;
+import org.apache.cassandra.locator.InetAddressAndPort;
+import org.apache.cassandra.net.MessagingService;
+import org.apache.cassandra.schema.MigrationManager;
+import org.apache.cassandra.service.PendingRangeCalculatorService;
+import org.apache.cassandra.service.StorageService;
+import org.apache.cassandra.utils.FBUtilities;
+
+import static org.apache.cassandra.distributed.impl.DistributedTestSnitch.toCassandraInetAddressAndPort;
+
+public class GossipHelper
+{
+ public static InstanceAction statusToBootstrap(IInvokableInstance newNode)
+ {
+ return (instance) ->
+ {
+ changeGossipState(instance,
+ newNode,
+ Arrays.asList(tokens(newNode),
+ statusBootstrapping(newNode),
+ statusWithPortBootstrapping(newNode)));
+ };
+ }
+
+ public static InstanceAction statusToNormal(IInvokableInstance peer)
+ {
+ return (target) ->
+ {
+ changeGossipState(target,
+ peer,
+ Arrays.asList(tokens(peer),
+ statusNormal(peer),
+ releaseVersion(peer),
+ netVersion(peer),
+ statusWithPortNormal(peer)));
+ };
+ }
+
+ /**
+ * This method is unsafe and should be used _only_ when gossip is not used or available: it creates versioned values on the
+ * target instance, which means Gossip versioning gets out of sync. Use a safe couterpart at all times when performing _any_
+ * ring movement operations _or_ if Gossip is used.
+ */
+ public static void unsafeStatusToNormal(IInvokableInstance target, IInstance peer)
+ {
+ int messagingVersion = peer.getMessagingVersion();
+ changeGossipState(target,
+ peer,
+ Arrays.asList(unsafeVersionedValue(target,
+ ApplicationState.TOKENS,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).tokens(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeVersionedValue(target,
+ ApplicationState.STATUS,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeVersionedValue(target,
+ ApplicationState.STATUS_WITH_PORT,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeVersionedValue(target,
+ ApplicationState.NET_VERSION,
+ (partitioner) -> new VersionedValue.VersionedValueFactory(partitioner).networkVersion(messagingVersion ),
+ peer.config().getString("partitioner")),
+ unsafeReleaseVersion(target,
+ peer.config().getString("partitioner"),
+ peer.getReleaseVersionString())));
+ }
+
+ public static InstanceAction statusToLeaving(IInvokableInstance newNode)
+ {
+ return (instance) -> {
+ changeGossipState(instance,
+ newNode,
+ Arrays.asList(tokens(newNode),
+ statusLeaving(newNode),
+ statusWithPortLeaving(newNode)));
+ };
+ }
+
+ public static InstanceAction bootstrap()
+ {
+ return new BootstrapAction();
+ }
+
+ public static InstanceAction bootstrap(boolean joinRing, Duration waitForBootstrap, Duration waitForSchema)
+ {
+ return new BootstrapAction(joinRing, waitForBootstrap, waitForSchema);
+ }
+
+ public static InstanceAction disseminateGossipState(IInvokableInstance newNode)
+ {
+ return new DisseminateGossipState(newNode);
+ }
+
+ public static InstanceAction pullSchemaFrom(IInvokableInstance pullFrom)
+ {
+ return new PullSchemaFrom(pullFrom);
+ }
+
+ private static InstanceAction disableBinary()
+ {
+ return (instance) -> instance.nodetoolResult("disablebinary").asserts().success();
+ }
+
+ private static class DisseminateGossipState implements InstanceAction
+ {
+ final Map<InetSocketAddress, byte[]> gossipState;
+
+ public DisseminateGossipState(IInvokableInstance... from)
+ {
+ gossipState = new HashMap<>();
+ for (IInvokableInstance node : from)
+ {
+ byte[] epBytes = node.callsOnInstance(() -> {
+ EndpointState epState = Gossiper.instance.getEndpointStateForEndpoint(FBUtilities.getBroadcastAddressAndPort());
+ return toBytes(epState);
+ }).call();
+ gossipState.put(node.broadcastAddress(), epBytes);
+ }
+ }
+
+ public void accept(IInvokableInstance instance)
+ {
+ instance.appliesOnInstance((IIsolatedExecutor.SerializableFunction<Map<InetSocketAddress, byte[]>, Void>)
+ (map) -> {
+ Map<InetAddressAndPort, EndpointState> newState = new HashMap<>();
+ for (Map.Entry<InetSocketAddress, byte[]> e : map.entrySet())
+ newState.put(toCassandraInetAddressAndPort(e.getKey()), fromBytes(e.getValue()));
+
+ Gossiper.runInGossipStageBlocking(() -> {
+ Gossiper.instance.applyStateLocally(newState);
+ });
+ return null;
+ }).apply(gossipState);
+ }
+ }
+
+ private static byte[] toBytes(EndpointState epState)
+ {
+ try (DataOutputBuffer out = new DataOutputBuffer(1024))
+ {
+ EndpointState.serializer.serialize(epState, out, MessagingService.current_version);
+ return out.toByteArray();
+ }
+ catch (IOException e)
+ {
+ throw new RuntimeException(e);
+ }
+ }
+
+ private static EndpointState fromBytes(byte[] bytes)
+ {
+ try (DataInputBuffer in = new DataInputBuffer(bytes))
+ {
+ return EndpointState.serializer.deserialize(in, MessagingService.current_version);
+ }
+ catch (Throwable t)
+ {
+ throw new RuntimeException(t);
+ }
+ }
+
+ private static class PullSchemaFrom implements InstanceAction
+ {
+ final InetSocketAddress pullFrom;
+
+ public PullSchemaFrom(IInvokableInstance pullFrom)
+ {
+ this.pullFrom = pullFrom.broadcastAddress();;
+ }
+
+ public void accept(IInvokableInstance pullTo)
+ {
+ pullTo.acceptsOnInstance((InetSocketAddress pullFrom) -> {
+ InetAddressAndPort endpoint = toCassandraInetAddressAndPort(pullFrom);
+ EndpointState state = Gossiper.instance.getEndpointStateForEndpoint(endpoint);
+ MigrationManager.scheduleSchemaPull(endpoint, state);
+ MigrationManager.waitUntilReadyForBootstrap();
+ }).accept(pullFrom);
+ }
+ }
+
+ private static class BootstrapAction implements InstanceAction, Serializable
+ {
+ private final boolean joinRing;
+ private final Duration waitForBootstrap;
+ private final Duration waitForSchema;
+
+ public BootstrapAction()
+ {
+ this(true, Duration.ofMinutes(10), Duration.ofSeconds(10));
+ }
+
+ public BootstrapAction(boolean joinRing, Duration waitForBootstrap, Duration waitForSchema)
+ {
+ this.joinRing = joinRing;
+ this.waitForBootstrap = waitForBootstrap;
+ this.waitForSchema = waitForSchema;
+ }
+
+ public void accept(IInvokableInstance instance)
+ {
+ instance.appliesOnInstance((String partitionerString, String tokenString) -> {
+ IPartitioner partitioner = FBUtilities.newPartitioner(partitionerString);
+ List<Token> tokens = Collections.singletonList(partitioner.getTokenFactory().fromString(tokenString));
+ try
+ {
+ SystemKeyspace.setBootstrapState(SystemKeyspace.BootstrapState.IN_PROGRESS);
+ StorageService.instance.waitForSchema(Math.toIntExact(waitForSchema.toMillis()));
+ PendingRangeCalculatorService.instance.blockUntilFinished();
+ StorageService.instance.startBootstrap(tokens).get(waitForBootstrap.toMillis(), TimeUnit.MILLISECONDS);
+ StorageService.instance.setUpDistributedSystemKeyspaces();
+ if (joinRing)
+ StorageService.instance.finishJoiningRing(true, tokens);
+ }
+ catch (Throwable t)
+ {
+ throw new RuntimeException(t);
+ }
+
+ return null;
+ }).apply(instance.config().getString("partitioner"), instance.config().getString("initial_token"));
+ }
+ }
+
+ public static InstanceAction decomission()
+ {
+ return (target) -> {
+ target.runOnInstance(() -> {
+ try
+ {
+ StorageService.instance.decommission(false);
+ }
+ catch (InterruptedException e)
+ {
+ throw new RuntimeException();
+ }
+ });
+ };
+ }
+
+
+ public static VersionedApplicationState tokens(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.TOKENS, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).tokens(tokens));
+ }
+
+ public static VersionedApplicationState netVersion(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.NET_VERSION, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).networkVersion());
+ }
+
+ public static VersionedApplicationState unsafeAppState(IInvokableInstance instance, ApplicationState applicationState, Supplier<VersionedValue> supplier)
+ {
+ return instance.callOnInstance(() -> {
+ VersionedValue versionedValue = supplier.get();
+ return new VersionedApplicationState(applicationState.ordinal(), versionedValue.value, versionedValue.version);
+ });
+ }
+
+ public static VersionedApplicationState unsafeReleaseVersion(IInvokableInstance instance, String partitionerStr, String releaseVersionStr)
+ {
+ return unsafeVersionedValue(instance, ApplicationState.RELEASE_VERSION, (partitioner) -> new VersionedValue.VersionedValueFactory(partitioner).releaseVersion(releaseVersionStr), partitionerStr);
+ }
+
+ public static VersionedApplicationState releaseVersion(IInvokableInstance instance)
+ {
+ return unsafeReleaseVersion(instance, instance.config().getString("partitioner"), instance.getReleaseVersionString());
+ }
+
+ public static VersionedApplicationState statusNormal(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens));
+ }
+
+ public static VersionedApplicationState statusWithPortNormal(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS_WITH_PORT, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens));
+ }
+
+ public static VersionedApplicationState statusBootstrapping(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).bootstrapping(tokens));
+ }
+
+ public static VersionedApplicationState statusWithPortBootstrapping(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS_WITH_PORT, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).bootstrapping(tokens));
+ }
+
+ public static VersionedApplicationState statusLeaving(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).leaving(tokens));
+ }
+
+ public static VersionedApplicationState statusLeft(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS, (partitioner, tokens) -> {
+ return new VersionedValue.VersionedValueFactory(partitioner).left(tokens, System.currentTimeMillis() + Gossiper.aVeryLongTime);
+
Review comment:
Sure; done!
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
[GitHub] [cassandra] dcapwell commented on a change in pull request #759: Improve machinery for testing bootstrap and range movements
Posted by GitBox <gi...@apache.org>.
dcapwell commented on a change in pull request #759:
URL: https://github.com/apache/cassandra/pull/759#discussion_r504189813
##########
File path: test/distributed/org/apache/cassandra/distributed/action/GossipHelper.java
##########
@@ -0,0 +1,464 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.distributed.action;
+
+
+import java.io.IOException;
+import java.net.InetSocketAddress;
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.TimeUnit;
+import java.util.function.Predicate;
+import java.util.stream.Stream;
+
+import net.openhft.chronicle.core.util.SerializableBiFunction;
+import net.openhft.chronicle.core.util.SerializableConsumer;
+import org.apache.cassandra.db.SystemKeyspace;
+import org.apache.cassandra.dht.IPartitioner;
+import org.apache.cassandra.dht.Token;
+import org.apache.cassandra.distributed.api.ICluster;
+import org.apache.cassandra.distributed.api.IInstance;
+import org.apache.cassandra.distributed.api.IInvokableInstance;
+import org.apache.cassandra.distributed.api.IIsolatedExecutor;
+import org.apache.cassandra.distributed.impl.Instance;
+import org.apache.cassandra.distributed.shared.VersionedApplicationState;
+import org.apache.cassandra.gms.ApplicationState;
+import org.apache.cassandra.gms.EndpointState;
+import org.apache.cassandra.gms.Gossiper;
+import org.apache.cassandra.gms.VersionedValue;
+import org.apache.cassandra.io.util.DataInputBuffer;
+import org.apache.cassandra.io.util.DataOutputBuffer;
+import org.apache.cassandra.locator.InetAddressAndPort;
+import org.apache.cassandra.locator.TokenMetadata;
+import org.apache.cassandra.net.MessagingService;
+import org.apache.cassandra.schema.MigrationManager;
+import org.apache.cassandra.service.PendingRangeCalculatorService;
+import org.apache.cassandra.service.StorageService;
+import org.apache.cassandra.utils.FBUtilities;
+
+import static org.apache.cassandra.distributed.impl.DistributedTestSnitch.toCassandraInetAddressAndPort;
+
+
+public class GossipHelper
+{
+
+ public static ClusterAction clusterAction(InstanceAction action)
Review comment:
One thing to notice, `Serializable` goes away in the patch since static methods don't have anything to capture, so the lambda in bootstrap doesn't grab hold of something that isn't `Serializable` so doesn't fail. It failed with the `BootstrapAction` as the lambda grabbed hold of `this` so required `this` to be `Serializable`; capturing lambdas... joy!
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
[GitHub] [cassandra] ifesdjeen commented on a change in pull request #759: Improve machinery for testing bootstrap and range movements
Posted by GitBox <gi...@apache.org>.
ifesdjeen commented on a change in pull request #759:
URL: https://github.com/apache/cassandra/pull/759#discussion_r504573574
##########
File path: test/distributed/org/apache/cassandra/distributed/test/BootstrapTest.java
##########
@@ -18,85 +18,241 @@
package org.apache.cassandra.distributed.test;
+import java.net.InetSocketAddress;
+import java.time.Duration;
+import java.util.HashMap;
+import java.util.HashSet;
import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.locks.LockSupport;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.junit.Assert;
import org.junit.Test;
+import com.datastax.driver.core.ResultSet;
+import com.datastax.driver.core.Session;
+import com.datastax.driver.core.SimpleStatement;
+import com.datastax.driver.core.Statement;
+import com.datastax.driver.core.policies.RoundRobinPolicy;
+import org.apache.cassandra.dht.Range;
+import org.apache.cassandra.dht.Token;
import org.apache.cassandra.distributed.Cluster;
import org.apache.cassandra.distributed.api.ConsistencyLevel;
import org.apache.cassandra.distributed.api.ICluster;
import org.apache.cassandra.distributed.api.IInstanceConfig;
+import org.apache.cassandra.distributed.api.IInvokableInstance;
import org.apache.cassandra.distributed.api.TokenSupplier;
+import org.apache.cassandra.distributed.impl.DistributedTestSnitch;
+import org.apache.cassandra.distributed.impl.RowUtil;
import org.apache.cassandra.distributed.shared.NetworkTopology;
+import org.apache.cassandra.locator.EndpointsForRange;
+import org.apache.cassandra.locator.InetAddressAndPort;
+import org.apache.cassandra.service.StorageService;
+import static org.apache.cassandra.distributed.action.GossipHelper.bootstrap;
+import static org.apache.cassandra.distributed.action.GossipHelper.decomission;
+import static org.apache.cassandra.distributed.action.GossipHelper.disseminateGossipState;
+import static org.apache.cassandra.distributed.action.GossipHelper.pullSchemaFrom;
+import static org.apache.cassandra.distributed.action.GossipHelper.statusToBootstrap;
import static org.apache.cassandra.distributed.api.Feature.GOSSIP;
+import static org.apache.cassandra.distributed.api.Feature.NATIVE_PROTOCOL;
import static org.apache.cassandra.distributed.api.Feature.NETWORK;
+import static org.apache.cassandra.distributed.shared.AssertUtils.assertRows;
+import static org.apache.cassandra.distributed.shared.AssertUtils.row;
-// TODO: this test should be removed after running in-jvm dtests is set up via the shared API repository
public class BootstrapTest extends TestBaseImpl
{
-
@Test
public void bootstrapTest() throws Throwable
{
int originalNodeCount = 2;
int expandedNodeCount = originalNodeCount + 1;
- Cluster.Builder builder = builder().withNodes(originalNodeCount)
- .withTokenSupplier(TokenSupplier.evenlyDistributedTokens(expandedNodeCount))
- .withNodeIdTopology(NetworkTopology.singleDcNetworkTopology(expandedNodeCount, "dc0", "rack0"))
- .withConfig(config -> config.with(NETWORK, GOSSIP));
-
- Map<Integer, Long> withBootstrap = null;
- Map<Integer, Long> naturally = null;
- try (Cluster cluster = builder.withNodes(originalNodeCount).start())
+
+ try (Cluster cluster = builder().withNodes(originalNodeCount)
+ .withTokenSupplier(TokenSupplier.evenlyDistributedTokens(expandedNodeCount))
+ .withNodeIdTopology(NetworkTopology.singleDcNetworkTopology(expandedNodeCount, "dc0", "rack0"))
+ .withConfig(config -> config.with(NETWORK, GOSSIP))
+ .start())
{
- populate(cluster);
+ populate(cluster,0, 100);
IInstanceConfig config = cluster.newInstanceConfig();
- config.set("auto_bootstrap", true);
-
- cluster.bootstrap(config).startup();
+ IInvokableInstance newInstance = cluster.initialize(config);
+ withJoinRing(false, () -> newInstance.startup(cluster));
- cluster.stream().forEach(instance -> {
- instance.nodetool("cleanup", KEYSPACE, "tbl");
- });
+ cluster.run(statusToBootstrap(newInstance));
+ cluster.run(pullSchemaFrom(cluster.get(1)), newInstance.config().num());
+ cluster.run(bootstrap(), newInstance.config().num());
- withBootstrap = count(cluster);
+ for (Map.Entry<Integer, Long> e : count(cluster).entrySet())
+ Assert.assertEquals(e.getValue().longValue(), 100L);
}
+ }
- builder = builder.withNodes(expandedNodeCount)
- .withTokenSupplier(TokenSupplier.evenlyDistributedTokens(expandedNodeCount))
- .withConfig(config -> config.with(NETWORK, GOSSIP));
+ @Test
+ public void testPendingWrites() throws Throwable
+ {
+ int originalNodeCount = 2;
+ int expandedNodeCount = originalNodeCount + 1;
- try (ICluster cluster = builder.start())
+ try (Cluster cluster = builder().withNodes(originalNodeCount)
+ .withTokenSupplier(TokenSupplier.evenlyDistributedTokens(expandedNodeCount))
+ .withNodeIdTopology(NetworkTopology.singleDcNetworkTopology(expandedNodeCount, "dc0", "rack0"))
+ .withConfig(config -> config.with(NETWORK, GOSSIP))
+ .start())
{
- populate(cluster);
- naturally = count(cluster);
+ populate(cluster, 0, 100);
+ IInstanceConfig config = cluster.newInstanceConfig();
+ IInvokableInstance newInstance = cluster.initialize(config);
+ withJoinRing(false, () -> newInstance.startup(cluster));
+
+ cluster.run(statusToBootstrap(newInstance));
+ cluster.run(bootstrap(false, Duration.ofSeconds(60), Duration.ofSeconds(60)), newInstance.config().num());
+
+ cluster.get(1).acceptsOnInstance((InetSocketAddress ip) -> {
+ Set<InetAddressAndPort> set = new HashSet<>();
+ for (Map.Entry<Range<Token>, EndpointsForRange.Builder> e : StorageService.instance.getTokenMetadata().getPendingRanges(KEYSPACE))
+ {
+ set.addAll(e.getValue().build().endpoints());
+ }
+ Assert.assertEquals(set.size(), 1);
+ Assert.assertTrue(String.format("%s should contain %s", set, ip),
+ set.contains(DistributedTestSnitch.toCassandraInetAddressAndPort(ip)));
+ }).accept(cluster.get(3).broadcastAddress());
+
+ populate(cluster, 100, 150);
+
+ newInstance.nodetoolResult("join").asserts().success();
+
+ cluster.run(disseminateGossipState(newInstance),1, 2);
+
+ cluster.get(1).acceptsOnInstance((InetSocketAddress ip) -> {
+ Set<InetAddressAndPort> set = new HashSet<>();
+ for (Map.Entry<Range<Token>, EndpointsForRange.Builder> e : StorageService.instance.getTokenMetadata().getPendingRanges(KEYSPACE))
+ set.addAll(e.getValue().build().endpoints());
+ assert set.size() == 0 : set;
+ }).accept(cluster.get(3).broadcastAddress());
+
+ for (Map.Entry<Integer, Long> e : count(cluster).entrySet())
+ Assert.assertEquals(e.getValue().longValue(), 150L);
}
+ }
+
+ @Test
+ public void internodeConnectionsDuringDecom() throws Throwable
+ {
+ try (Cluster cluster = builder().withNodes(4)
+ .withConfig(config -> config.with(NETWORK, GOSSIP, NATIVE_PROTOCOL))
+ .start())
+ {
+ populate(cluster, 0, 100);
+
+ cluster.run(decomission(), 1);
- for (Map.Entry<Integer, Long> e : withBootstrap.entrySet())
- Assert.assertTrue(e.getValue() >= naturally.get(e.getKey()));
+ cluster.filters().allVerbs().from(1).messagesMatching((i, i1, iMessage) -> {
+ throw new AssertionError("Decomissioned node should not send any messages");
+ }).drop();
+
+
+ Map<Integer, Long> connectionAttempts = new HashMap<>();
+ long deadline = System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(10);
+
+ // Wait 10 seconds and check if there are any new connection attempts to the decomissioned node
+ while (System.currentTimeMillis() <= deadline)
+ {
+ for (int i = 2; i <= cluster.size(); i++)
+ {
+ Object[][] res = cluster.get(i).executeInternal("SELECT active_connections, connection_attempts FROM system_views.internode_outbound WHERE address = '127.0.0.1' AND port = 7012");
+ Assert.assertEquals(1, res.length);
+ Assert.assertEquals(0L, ((Long) res[0][0]).longValue());
+ long attempts = ((Long) res[0][1]).longValue();
+ if (connectionAttempts.get(i) == null)
+ connectionAttempts.put(i, attempts);
+ else
+ Assert.assertEquals(connectionAttempts.get(i), (Long) attempts);
+ }
+ LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(100));
+ }
+ }
}
- public void populate(ICluster cluster)
+ @Test
+ public void clientConnectionsDuringDecom() throws Throwable
{
- cluster.schemaChange("CREATE KEYSPACE " + KEYSPACE + " WITH replication = {'class': 'SimpleStrategy', 'replication_factor': " + 3 + "};");
- cluster.schemaChange("CREATE TABLE " + KEYSPACE + ".tbl (pk int, ck int, v int, PRIMARY KEY (pk, ck))");
+ ExecutorService executor = Executors.newFixedThreadPool(1);
+ try (Cluster cluster = builder().withNodes(4)
+ .withConfig(config -> config.with(NETWORK, GOSSIP, NATIVE_PROTOCOL))
+ .start())
+ {
+ populate(cluster, 0, 100);
+
+ try (com.datastax.driver.core.Cluster client = com.datastax.driver.core.Cluster.builder().addContactPoint("127.0.0.1")
+ .withLoadBalancingPolicy(new RoundRobinPolicy())
+ .build();
+ Session session = client.connect())
+ {
+ CompletableFuture.runAsync(() -> {
+ while (!Thread.currentThread().isInterrupted())
+ {
+ if (client.getMetadata().getAllHosts().size() == cluster.size())
+ return;
+ LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(100));
+ }
+ }, executor).get(1, TimeUnit.MINUTES);
+
+ cluster.run(decomission(), 1);
+
+ Assert.assertEquals(cluster.size() - 1, client.getMetadata().getAllHosts().size());
Review comment:
Client runs `onDown` on disconnect. So I think this should be fine, given we know connection was closed.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
[GitHub] [cassandra] dcapwell commented on a change in pull request #759: Improve machinery for testing bootstrap and range movements
Posted by GitBox <gi...@apache.org>.
dcapwell commented on a change in pull request #759:
URL: https://github.com/apache/cassandra/pull/759#discussion_r508730857
##########
File path: test/distributed/org/apache/cassandra/distributed/action/GossipHelper.java
##########
@@ -0,0 +1,462 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.distributed.action;
+
+import java.io.IOException;
+import java.io.Serializable;
+import java.net.InetSocketAddress;
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.TimeUnit;
+import java.util.function.Supplier;
+
+import org.apache.cassandra.db.SystemKeyspace;
+import org.apache.cassandra.dht.IPartitioner;
+import org.apache.cassandra.dht.Token;
+import org.apache.cassandra.distributed.api.IInstance;
+import org.apache.cassandra.distributed.api.IInvokableInstance;
+import org.apache.cassandra.distributed.api.IIsolatedExecutor;
+import org.apache.cassandra.distributed.shared.VersionedApplicationState;
+import org.apache.cassandra.gms.ApplicationState;
+import org.apache.cassandra.gms.EndpointState;
+import org.apache.cassandra.gms.Gossiper;
+import org.apache.cassandra.gms.VersionedValue;
+import org.apache.cassandra.io.util.DataInputBuffer;
+import org.apache.cassandra.io.util.DataOutputBuffer;
+import org.apache.cassandra.locator.InetAddressAndPort;
+import org.apache.cassandra.net.MessagingService;
+import org.apache.cassandra.schema.MigrationManager;
+import org.apache.cassandra.service.PendingRangeCalculatorService;
+import org.apache.cassandra.service.StorageService;
+import org.apache.cassandra.utils.FBUtilities;
+
+import static org.apache.cassandra.distributed.impl.DistributedTestSnitch.toCassandraInetAddressAndPort;
+
+public class GossipHelper
+{
+ public static InstanceAction statusToBootstrap(IInvokableInstance newNode)
+ {
+ return (instance) ->
+ {
+ changeGossipState(instance,
+ newNode,
+ Arrays.asList(tokens(newNode),
+ statusBootstrapping(newNode),
+ statusWithPortBootstrapping(newNode)));
+ };
+ }
+
+ public static InstanceAction statusToNormal(IInvokableInstance peer)
+ {
+ return (target) ->
+ {
+ changeGossipState(target,
+ peer,
+ Arrays.asList(tokens(peer),
+ statusNormal(peer),
+ releaseVersion(peer),
+ netVersion(peer),
+ statusWithPortNormal(peer)));
+ };
+ }
+
+ /**
+ * This method is unsafe and should be used _only_ when gossip is not used or available: it creates versioned values on the
+ * target instance, which means Gossip versioning gets out of sync. Use a safe couterpart at all times when performing _any_
+ * ring movement operations _or_ if Gossip is used.
+ */
+ public static void unsafeStatusToNormal(IInvokableInstance target, IInstance peer)
+ {
+ int messagingVersion = peer.getMessagingVersion();
+ changeGossipState(target,
+ peer,
+ Arrays.asList(unsafeVersionedValue(target,
+ ApplicationState.TOKENS,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).tokens(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeVersionedValue(target,
+ ApplicationState.STATUS,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeVersionedValue(target,
+ ApplicationState.STATUS_WITH_PORT,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeVersionedValue(target,
+ ApplicationState.NET_VERSION,
+ (partitioner) -> new VersionedValue.VersionedValueFactory(partitioner).networkVersion(messagingVersion ),
+ peer.config().getString("partitioner")),
+ unsafeReleaseVersion(target,
+ peer.config().getString("partitioner"),
+ peer.getReleaseVersionString())));
+ }
+
+ public static InstanceAction statusToLeaving(IInvokableInstance newNode)
+ {
+ return (instance) -> {
+ changeGossipState(instance,
+ newNode,
+ Arrays.asList(tokens(newNode),
+ statusLeaving(newNode),
+ statusWithPortLeaving(newNode)));
+ };
+ }
+
+ public static InstanceAction bootstrap()
+ {
+ return new BootstrapAction();
+ }
+
+ public static InstanceAction bootstrap(boolean joinRing, Duration waitForBootstrap, Duration waitForSchema)
+ {
+ return new BootstrapAction(joinRing, waitForBootstrap, waitForSchema);
+ }
+
+ public static InstanceAction disseminateGossipState(IInvokableInstance newNode)
+ {
+ return new DisseminateGossipState(newNode);
+ }
+
+ public static InstanceAction pullSchemaFrom(IInvokableInstance pullFrom)
+ {
+ return new PullSchemaFrom(pullFrom);
+ }
+
+ private static InstanceAction disableBinary()
+ {
+ return (instance) -> instance.nodetoolResult("disablebinary").asserts().success();
+ }
+
+ private static class DisseminateGossipState implements InstanceAction
+ {
+ final Map<InetSocketAddress, byte[]> gossipState;
+
+ public DisseminateGossipState(IInvokableInstance... from)
+ {
+ gossipState = new HashMap<>();
+ for (IInvokableInstance node : from)
+ {
+ byte[] epBytes = node.callsOnInstance(() -> {
+ EndpointState epState = Gossiper.instance.getEndpointStateForEndpoint(FBUtilities.getBroadcastAddressAndPort());
+ return toBytes(epState);
+ }).call();
+ gossipState.put(node.broadcastAddress(), epBytes);
+ }
+ }
+
+ public void accept(IInvokableInstance instance)
+ {
+ instance.appliesOnInstance((IIsolatedExecutor.SerializableFunction<Map<InetSocketAddress, byte[]>, Void>)
+ (map) -> {
+ Map<InetAddressAndPort, EndpointState> newState = new HashMap<>();
+ for (Map.Entry<InetSocketAddress, byte[]> e : map.entrySet())
+ newState.put(toCassandraInetAddressAndPort(e.getKey()), fromBytes(e.getValue()));
+
+ Gossiper.runInGossipStageBlocking(() -> {
+ Gossiper.instance.applyStateLocally(newState);
+ });
+ return null;
+ }).apply(gossipState);
+ }
+ }
+
+ private static byte[] toBytes(EndpointState epState)
+ {
+ try (DataOutputBuffer out = new DataOutputBuffer(1024))
+ {
+ EndpointState.serializer.serialize(epState, out, MessagingService.current_version);
+ return out.toByteArray();
+ }
+ catch (IOException e)
+ {
+ throw new RuntimeException(e);
+ }
+ }
+
+ private static EndpointState fromBytes(byte[] bytes)
+ {
+ try (DataInputBuffer in = new DataInputBuffer(bytes))
+ {
+ return EndpointState.serializer.deserialize(in, MessagingService.current_version);
+ }
+ catch (Throwable t)
+ {
+ throw new RuntimeException(t);
+ }
+ }
+
+ private static class PullSchemaFrom implements InstanceAction
+ {
+ final InetSocketAddress pullFrom;
+
+ public PullSchemaFrom(IInvokableInstance pullFrom)
+ {
+ this.pullFrom = pullFrom.broadcastAddress();;
+ }
+
+ public void accept(IInvokableInstance pullTo)
+ {
+ pullTo.acceptsOnInstance((InetSocketAddress pullFrom) -> {
+ InetAddressAndPort endpoint = toCassandraInetAddressAndPort(pullFrom);
+ EndpointState state = Gossiper.instance.getEndpointStateForEndpoint(endpoint);
+ MigrationManager.scheduleSchemaPull(endpoint, state);
+ MigrationManager.waitUntilReadyForBootstrap();
+ }).accept(pullFrom);
+ }
+ }
+
+ private static class BootstrapAction implements InstanceAction, Serializable
+ {
+ private final boolean joinRing;
+ private final Duration waitForBootstrap;
+ private final Duration waitForSchema;
+
+ public BootstrapAction()
+ {
+ this(true, Duration.ofMinutes(10), Duration.ofSeconds(10));
+ }
+
+ public BootstrapAction(boolean joinRing, Duration waitForBootstrap, Duration waitForSchema)
+ {
+ this.joinRing = joinRing;
+ this.waitForBootstrap = waitForBootstrap;
+ this.waitForSchema = waitForSchema;
+ }
+
+ public void accept(IInvokableInstance instance)
+ {
+ instance.appliesOnInstance((String partitionerString, String tokenString) -> {
+ IPartitioner partitioner = FBUtilities.newPartitioner(partitionerString);
+ List<Token> tokens = Collections.singletonList(partitioner.getTokenFactory().fromString(tokenString));
+ try
+ {
+ SystemKeyspace.setBootstrapState(SystemKeyspace.BootstrapState.IN_PROGRESS);
+ StorageService.instance.waitForSchema(Math.toIntExact(waitForSchema.toMillis()));
+ PendingRangeCalculatorService.instance.blockUntilFinished();
+ StorageService.instance.startBootstrap(tokens).get(waitForBootstrap.toMillis(), TimeUnit.MILLISECONDS);
+ StorageService.instance.setUpDistributedSystemKeyspaces();
+ if (joinRing)
+ StorageService.instance.finishJoiningRing(true, tokens);
+ }
+ catch (Throwable t)
+ {
+ throw new RuntimeException(t);
+ }
+
+ return null;
+ }).apply(instance.config().getString("partitioner"), instance.config().getString("initial_token"));
+ }
+ }
+
+ public static InstanceAction decomission()
+ {
+ return (target) -> {
+ target.runOnInstance(() -> {
+ try
+ {
+ StorageService.instance.decommission(false);
+ }
+ catch (InterruptedException e)
+ {
+ throw new RuntimeException();
+ }
+ });
+ };
+ }
+
+
+ public static VersionedApplicationState tokens(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.TOKENS, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).tokens(tokens));
+ }
+
+ public static VersionedApplicationState netVersion(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.NET_VERSION, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).networkVersion());
+ }
+
+ public static VersionedApplicationState unsafeAppState(IInvokableInstance instance, ApplicationState applicationState, Supplier<VersionedValue> supplier)
Review comment:
this looks unused and the supplier isn't Serializable, so shouldn't callOnInstance fail?
##########
File path: test/distributed/org/apache/cassandra/distributed/action/GossipHelper.java
##########
@@ -0,0 +1,462 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.distributed.action;
+
+import java.io.IOException;
+import java.io.Serializable;
+import java.net.InetSocketAddress;
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.TimeUnit;
+import java.util.function.Supplier;
+
+import org.apache.cassandra.db.SystemKeyspace;
+import org.apache.cassandra.dht.IPartitioner;
+import org.apache.cassandra.dht.Token;
+import org.apache.cassandra.distributed.api.IInstance;
+import org.apache.cassandra.distributed.api.IInvokableInstance;
+import org.apache.cassandra.distributed.api.IIsolatedExecutor;
+import org.apache.cassandra.distributed.shared.VersionedApplicationState;
+import org.apache.cassandra.gms.ApplicationState;
+import org.apache.cassandra.gms.EndpointState;
+import org.apache.cassandra.gms.Gossiper;
+import org.apache.cassandra.gms.VersionedValue;
+import org.apache.cassandra.io.util.DataInputBuffer;
+import org.apache.cassandra.io.util.DataOutputBuffer;
+import org.apache.cassandra.locator.InetAddressAndPort;
+import org.apache.cassandra.net.MessagingService;
+import org.apache.cassandra.schema.MigrationManager;
+import org.apache.cassandra.service.PendingRangeCalculatorService;
+import org.apache.cassandra.service.StorageService;
+import org.apache.cassandra.utils.FBUtilities;
+
+import static org.apache.cassandra.distributed.impl.DistributedTestSnitch.toCassandraInetAddressAndPort;
+
+public class GossipHelper
+{
+ public static InstanceAction statusToBootstrap(IInvokableInstance newNode)
+ {
+ return (instance) ->
+ {
+ changeGossipState(instance,
+ newNode,
+ Arrays.asList(tokens(newNode),
+ statusBootstrapping(newNode),
+ statusWithPortBootstrapping(newNode)));
+ };
+ }
+
+ public static InstanceAction statusToNormal(IInvokableInstance peer)
+ {
+ return (target) ->
+ {
+ changeGossipState(target,
+ peer,
+ Arrays.asList(tokens(peer),
+ statusNormal(peer),
+ releaseVersion(peer),
+ netVersion(peer),
+ statusWithPortNormal(peer)));
+ };
+ }
+
+ /**
+ * This method is unsafe and should be used _only_ when gossip is not used or available: it creates versioned values on the
+ * target instance, which means Gossip versioning gets out of sync. Use a safe couterpart at all times when performing _any_
+ * ring movement operations _or_ if Gossip is used.
+ */
+ public static void unsafeStatusToNormal(IInvokableInstance target, IInstance peer)
+ {
+ int messagingVersion = peer.getMessagingVersion();
+ changeGossipState(target,
+ peer,
+ Arrays.asList(unsafeVersionedValue(target,
+ ApplicationState.TOKENS,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).tokens(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeVersionedValue(target,
+ ApplicationState.STATUS,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeVersionedValue(target,
+ ApplicationState.STATUS_WITH_PORT,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeVersionedValue(target,
+ ApplicationState.NET_VERSION,
+ (partitioner) -> new VersionedValue.VersionedValueFactory(partitioner).networkVersion(messagingVersion ),
+ peer.config().getString("partitioner")),
+ unsafeReleaseVersion(target,
+ peer.config().getString("partitioner"),
+ peer.getReleaseVersionString())));
+ }
+
+ public static InstanceAction statusToLeaving(IInvokableInstance newNode)
+ {
+ return (instance) -> {
+ changeGossipState(instance,
+ newNode,
+ Arrays.asList(tokens(newNode),
+ statusLeaving(newNode),
+ statusWithPortLeaving(newNode)));
+ };
+ }
+
+ public static InstanceAction bootstrap()
+ {
+ return new BootstrapAction();
+ }
+
+ public static InstanceAction bootstrap(boolean joinRing, Duration waitForBootstrap, Duration waitForSchema)
+ {
+ return new BootstrapAction(joinRing, waitForBootstrap, waitForSchema);
+ }
+
+ public static InstanceAction disseminateGossipState(IInvokableInstance newNode)
+ {
+ return new DisseminateGossipState(newNode);
+ }
+
+ public static InstanceAction pullSchemaFrom(IInvokableInstance pullFrom)
+ {
+ return new PullSchemaFrom(pullFrom);
+ }
+
+ private static InstanceAction disableBinary()
+ {
+ return (instance) -> instance.nodetoolResult("disablebinary").asserts().success();
+ }
+
+ private static class DisseminateGossipState implements InstanceAction
+ {
+ final Map<InetSocketAddress, byte[]> gossipState;
+
+ public DisseminateGossipState(IInvokableInstance... from)
+ {
+ gossipState = new HashMap<>();
+ for (IInvokableInstance node : from)
+ {
+ byte[] epBytes = node.callsOnInstance(() -> {
+ EndpointState epState = Gossiper.instance.getEndpointStateForEndpoint(FBUtilities.getBroadcastAddressAndPort());
+ return toBytes(epState);
+ }).call();
+ gossipState.put(node.broadcastAddress(), epBytes);
+ }
+ }
+
+ public void accept(IInvokableInstance instance)
+ {
+ instance.appliesOnInstance((IIsolatedExecutor.SerializableFunction<Map<InetSocketAddress, byte[]>, Void>)
+ (map) -> {
+ Map<InetAddressAndPort, EndpointState> newState = new HashMap<>();
+ for (Map.Entry<InetSocketAddress, byte[]> e : map.entrySet())
+ newState.put(toCassandraInetAddressAndPort(e.getKey()), fromBytes(e.getValue()));
+
+ Gossiper.runInGossipStageBlocking(() -> {
+ Gossiper.instance.applyStateLocally(newState);
+ });
+ return null;
+ }).apply(gossipState);
+ }
+ }
+
+ private static byte[] toBytes(EndpointState epState)
+ {
+ try (DataOutputBuffer out = new DataOutputBuffer(1024))
+ {
+ EndpointState.serializer.serialize(epState, out, MessagingService.current_version);
+ return out.toByteArray();
+ }
+ catch (IOException e)
+ {
+ throw new RuntimeException(e);
+ }
+ }
+
+ private static EndpointState fromBytes(byte[] bytes)
+ {
+ try (DataInputBuffer in = new DataInputBuffer(bytes))
+ {
+ return EndpointState.serializer.deserialize(in, MessagingService.current_version);
+ }
+ catch (Throwable t)
+ {
+ throw new RuntimeException(t);
+ }
+ }
+
+ private static class PullSchemaFrom implements InstanceAction
+ {
+ final InetSocketAddress pullFrom;
+
+ public PullSchemaFrom(IInvokableInstance pullFrom)
+ {
+ this.pullFrom = pullFrom.broadcastAddress();;
+ }
+
+ public void accept(IInvokableInstance pullTo)
+ {
+ pullTo.acceptsOnInstance((InetSocketAddress pullFrom) -> {
+ InetAddressAndPort endpoint = toCassandraInetAddressAndPort(pullFrom);
+ EndpointState state = Gossiper.instance.getEndpointStateForEndpoint(endpoint);
+ MigrationManager.scheduleSchemaPull(endpoint, state);
+ MigrationManager.waitUntilReadyForBootstrap();
+ }).accept(pullFrom);
+ }
+ }
+
+ private static class BootstrapAction implements InstanceAction, Serializable
+ {
+ private final boolean joinRing;
+ private final Duration waitForBootstrap;
+ private final Duration waitForSchema;
+
+ public BootstrapAction()
+ {
+ this(true, Duration.ofMinutes(10), Duration.ofSeconds(10));
+ }
+
+ public BootstrapAction(boolean joinRing, Duration waitForBootstrap, Duration waitForSchema)
+ {
+ this.joinRing = joinRing;
+ this.waitForBootstrap = waitForBootstrap;
+ this.waitForSchema = waitForSchema;
+ }
+
+ public void accept(IInvokableInstance instance)
+ {
+ instance.appliesOnInstance((String partitionerString, String tokenString) -> {
+ IPartitioner partitioner = FBUtilities.newPartitioner(partitionerString);
+ List<Token> tokens = Collections.singletonList(partitioner.getTokenFactory().fromString(tokenString));
+ try
+ {
+ SystemKeyspace.setBootstrapState(SystemKeyspace.BootstrapState.IN_PROGRESS);
+ StorageService.instance.waitForSchema(Math.toIntExact(waitForSchema.toMillis()));
+ PendingRangeCalculatorService.instance.blockUntilFinished();
+ StorageService.instance.startBootstrap(tokens).get(waitForBootstrap.toMillis(), TimeUnit.MILLISECONDS);
+ StorageService.instance.setUpDistributedSystemKeyspaces();
+ if (joinRing)
+ StorageService.instance.finishJoiningRing(true, tokens);
+ }
+ catch (Throwable t)
+ {
+ throw new RuntimeException(t);
+ }
+
+ return null;
+ }).apply(instance.config().getString("partitioner"), instance.config().getString("initial_token"));
+ }
+ }
+
+ public static InstanceAction decomission()
+ {
+ return (target) -> {
+ target.runOnInstance(() -> {
+ try
+ {
+ StorageService.instance.decommission(false);
+ }
+ catch (InterruptedException e)
+ {
+ throw new RuntimeException();
+ }
+ });
+ };
+ }
+
+
+ public static VersionedApplicationState tokens(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.TOKENS, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).tokens(tokens));
+ }
+
+ public static VersionedApplicationState netVersion(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.NET_VERSION, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).networkVersion());
+ }
+
+ public static VersionedApplicationState unsafeAppState(IInvokableInstance instance, ApplicationState applicationState, Supplier<VersionedValue> supplier)
+ {
+ return instance.callOnInstance(() -> {
+ VersionedValue versionedValue = supplier.get();
+ return new VersionedApplicationState(applicationState.ordinal(), versionedValue.value, versionedValue.version);
+ });
+ }
+
+ public static VersionedApplicationState unsafeReleaseVersion(IInvokableInstance instance, String partitionerStr, String releaseVersionStr)
+ {
+ return unsafeVersionedValue(instance, ApplicationState.RELEASE_VERSION, (partitioner) -> new VersionedValue.VersionedValueFactory(partitioner).releaseVersion(releaseVersionStr), partitionerStr);
+ }
+
+ public static VersionedApplicationState releaseVersion(IInvokableInstance instance)
+ {
+ return unsafeReleaseVersion(instance, instance.config().getString("partitioner"), instance.getReleaseVersionString());
+ }
+
+ public static VersionedApplicationState statusNormal(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens));
+ }
+
+ public static VersionedApplicationState statusWithPortNormal(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS_WITH_PORT, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens));
+ }
+
+ public static VersionedApplicationState statusBootstrapping(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).bootstrapping(tokens));
+ }
+
+ public static VersionedApplicationState statusWithPortBootstrapping(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS_WITH_PORT, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).bootstrapping(tokens));
+ }
+
+ public static VersionedApplicationState statusLeaving(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).leaving(tokens));
+ }
+
+ public static VersionedApplicationState statusLeft(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS, (partitioner, tokens) -> {
+ return new VersionedValue.VersionedValueFactory(partitioner).left(tokens, System.currentTimeMillis() + Gossiper.aVeryLongTime);
+
Review comment:
can you remove the space?
##########
File path: test/distributed/org/apache/cassandra/distributed/action/GossipHelper.java
##########
@@ -0,0 +1,431 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.distributed.action;
+
+import java.io.IOException;
+import java.io.Serializable;
+import java.net.InetSocketAddress;
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.TimeUnit;
+import java.util.stream.Stream;
+
+import net.openhft.chronicle.core.util.SerializableBiFunction;
+import org.apache.cassandra.db.SystemKeyspace;
+import org.apache.cassandra.dht.IPartitioner;
+import org.apache.cassandra.dht.Token;
+import org.apache.cassandra.distributed.api.IInstance;
+import org.apache.cassandra.distributed.api.IInvokableInstance;
+import org.apache.cassandra.distributed.api.IIsolatedExecutor;
+import org.apache.cassandra.distributed.impl.Instance;
+import org.apache.cassandra.distributed.shared.VersionedApplicationState;
+import org.apache.cassandra.gms.ApplicationState;
+import org.apache.cassandra.gms.EndpointState;
+import org.apache.cassandra.gms.Gossiper;
+import org.apache.cassandra.gms.VersionedValue;
+import org.apache.cassandra.io.util.DataInputBuffer;
+import org.apache.cassandra.io.util.DataOutputBuffer;
+import org.apache.cassandra.locator.InetAddressAndPort;
+import org.apache.cassandra.locator.TokenMetadata;
+import org.apache.cassandra.net.MessagingService;
+import org.apache.cassandra.schema.MigrationManager;
+import org.apache.cassandra.service.PendingRangeCalculatorService;
+import org.apache.cassandra.service.StorageService;
+import org.apache.cassandra.utils.FBUtilities;
+
+import static org.apache.cassandra.distributed.impl.DistributedTestSnitch.toCassandraInetAddressAndPort;
+
+public class GossipHelper
+{
+ public static InstanceAction statusToBootstrap(IInvokableInstance newNode)
+ {
+ return (instance) ->
+ {
+ changeGossipState(instance,
+ newNode,
+ Arrays.asList(tokens(newNode),
+ statusBootstrapping(newNode),
+ statusWithPortBootstrapping(newNode)));
+ };
+ }
+
+ public static InstanceAction statusToNormal(IInvokableInstance peer)
+ {
+ return (target) ->
+ {
+ changeGossipState(target,
+ peer,
+ Arrays.asList(tokens(peer),
+ statusNormal(peer),
+ releaseVersion(peer),
+ statusWithPortNormal(peer)));
+ };
+ }
+
+ /**
+ * This method is unsafe and should be used _only_ when gossip is not used or available: it creates versioned values on the
+ * target instance, which means Gossip versioning gets out of sync. Use a safe couterpart at all times when performing _any_
+ * ring movement operations _or_ if Gossip is used.
+ */
+ public static InstanceAction unsafeStatusToNormal(IInstance peer)
+ {
+ return (target) ->
+ {
+ changeGossipState(target,
+ peer,
+ Arrays.asList(unsafeVersionedToken(target,
+ ApplicationState.TOKENS,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).tokens(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeVersionedToken(target,
+ ApplicationState.STATUS,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeVersionedToken(target,
+ ApplicationState.STATUS_WITH_PORT,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeReleaseVersion(target,
+ peer.config().getString("partitioner"),
+ peer.getReleaseVersionString())));
+ };
+ }
+
+ public static InstanceAction statusToLeaving(IInvokableInstance newNode)
+ {
+ return (instance) -> {
+ changeGossipState(instance,
+ newNode,
+ Arrays.asList(tokens(newNode),
+ statusLeaving(newNode),
+ statusWithPortLeaving(newNode)));
+ };
+ }
+
+ public static InstanceAction bootstrap()
+ {
+ return new BootstrapAction();
+ }
+
+ public static InstanceAction bootstrap(boolean joinRing, Duration waitForBootstrap, Duration waitForSchema)
+ {
+ return new BootstrapAction(joinRing, waitForBootstrap, waitForSchema);
+ }
+
+ public static InstanceAction disseminateGossipState(IInvokableInstance newNode)
+ {
+ return new DisseminateGossipState(newNode);
+ }
+
+ public static InstanceAction pullSchemaFrom(IInvokableInstance pullFrom)
+ {
+ return new PullSchemaFrom(pullFrom);
+ }
+
+ private static InstanceAction disableBinary()
+ {
+ return (instance) -> {
+ instance.runOnInstance(StorageService.instance::stopNativeTransport);
+ };
+ }
+
+ private static class DisseminateGossipState implements InstanceAction
+ {
+ final Map<InetSocketAddress, byte[]> gossipState;
+
+ public DisseminateGossipState(IInvokableInstance... from)
+ {
+ gossipState = new HashMap<>();
+ for (IInvokableInstance node : from)
+ {
+ byte[] epBytes = node.callsOnInstance(() -> {
+ EndpointState epState = Gossiper.instance.getEndpointStateForEndpoint(FBUtilities.getBroadcastAddressAndPort());
+ return toBytes(epState);
+ }).call();
+ gossipState.put(node.broadcastAddress(), epBytes);
+ }
+ }
+
+ public void accept(IInvokableInstance instance)
+ {
+ instance.appliesOnInstance((IIsolatedExecutor.SerializableFunction<Map<InetSocketAddress, byte[]>, Void>)
+ (map) -> {
+ Map<InetAddressAndPort, EndpointState> newState = new HashMap<>();
+ for (Map.Entry<InetSocketAddress, byte[]> e : map.entrySet())
+ newState.put(toCassandraInetAddressAndPort(e.getKey()), fromBytes(e.getValue()));
+
+ Gossiper.runInGossipStageBlocking(() -> {
+ Gossiper.instance.applyStateLocally(newState);
+ });
+ return null;
+ }).apply(gossipState);
+ }
+ }
+
+ public static byte[] toBytes(EndpointState epState)
+ {
+ try (DataOutputBuffer out = new DataOutputBuffer(1024))
+ {
+ EndpointState.serializer.serialize(epState, out, MessagingService.current_version);
+ return out.toByteArray();
+ }
+ catch (IOException e)
+ {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public static EndpointState fromBytes(byte[] bytes)
+ {
+ try (DataInputBuffer in = new DataInputBuffer(bytes))
+ {
+ return EndpointState.serializer.deserialize(in, MessagingService.current_version);
+ }
+ catch (Throwable t)
+ {
+ throw new RuntimeException(t);
+ }
+ }
+
+ private static class PullSchemaFrom implements InstanceAction
+ {
+ final InetSocketAddress pullFrom;
+
+ public PullSchemaFrom(IInvokableInstance pullFrom)
+ {
+ this.pullFrom = pullFrom.broadcastAddress();;
+ }
+
+ public void accept(IInvokableInstance pullTo)
+ {
+ pullTo.acceptsOnInstance((InetSocketAddress pullFrom) -> {
+ InetAddressAndPort endpoint = toCassandraInetAddressAndPort(pullFrom);
+ EndpointState state = Gossiper.instance.getEndpointStateForEndpoint(endpoint);
+ MigrationManager.scheduleSchemaPull(endpoint, state);
+ MigrationManager.waitUntilReadyForBootstrap();
+ }).accept(pullFrom);
+ }
+ }
+
+ private static class BootstrapAction implements InstanceAction, Serializable
+ {
+ private final boolean joinRing;
+ private final Duration waitForBootstrap;
+ private final Duration waitForSchema;
+
+ public BootstrapAction()
+ {
+ this(true, Duration.ofMinutes(10), Duration.ofSeconds(10));
+ }
+
+ public BootstrapAction(boolean joinRing, Duration waitForBootstrap, Duration waitForSchema)
+ {
+ this.joinRing = joinRing;
+ this.waitForBootstrap = waitForBootstrap;
+ this.waitForSchema = waitForSchema;
+ }
+
+ public void accept(IInvokableInstance instance)
+ {
+ instance.appliesOnInstance((String partitionerString, String tokenString) -> {
+ IPartitioner partitioner = FBUtilities.newPartitioner(partitionerString);
+ List<Token> tokens = Collections.singletonList(partitioner.getTokenFactory().fromString(tokenString));
+ try
+ {
+ SystemKeyspace.setBootstrapState(SystemKeyspace.BootstrapState.IN_PROGRESS);
+ StorageService.instance.waitForSchema((int) waitForSchema.toMillis());
+ PendingRangeCalculatorService.instance.blockUntilFinished();
+ StorageService.instance.startBootstrap(tokens).get(waitForBootstrap.toMillis(), TimeUnit.MILLISECONDS);
+ StorageService.instance.setUpDistributedSystemKeyspaces();
+ if (joinRing)
+ StorageService.instance.finishJoiningRing(true, tokens);
+ }
+ catch (Throwable t)
+ {
+ throw new RuntimeException(t);
+ }
+
+ return null;
+ }).apply(instance.config().getString("partitioner"), instance.config().getString("initial_token"));
+ }
+ }
+
+ public static InstanceAction decomission()
+ {
+ return (target) -> {
+ target.runOnInstance(() -> {
+ try
+ {
+ StorageService.instance.decommission(false);
+ }
+ catch (InterruptedException e)
+ {
+ throw new RuntimeException();
+ }
+ });
+ };
+ }
+
+
+ public static VersionedApplicationState tokens(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.TOKENS, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).tokens(tokens));
+ }
+
+ public static VersionedApplicationState unsafeReleaseVersion(IInvokableInstance instance, String partitionerStr, String releaseVersionStr)
+ {
+ return instance.appliesOnInstance((String partitionerString, String releaseVersion) -> {
+ IPartitioner partitioner = FBUtilities.newPartitioner(partitionerString);
+ VersionedValue versionedValue = new VersionedValue.VersionedValueFactory(partitioner).releaseVersion(releaseVersion);
+ return new VersionedApplicationState(ApplicationState.RELEASE_VERSION.ordinal(), versionedValue.value, versionedValue.version);
+ }).apply(partitionerStr, releaseVersionStr);
+ }
+
+ public static VersionedApplicationState releaseVersion(IInvokableInstance instance)
+ {
+ return unsafeReleaseVersion(instance, instance.config().getString("partitioner"), instance.getReleaseVersionString());
+ }
+
+ public static VersionedApplicationState statusNormal(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens));
+ }
+
+ public static VersionedApplicationState statusWithPortNormal(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS_WITH_PORT, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens));
+ }
+
+ public static VersionedApplicationState statusBootstrapping(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).bootstrapping(tokens));
+ }
+
+ public static VersionedApplicationState statusWithPortBootstrapping(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS_WITH_PORT, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).bootstrapping(tokens));
+ }
+
+ public static VersionedApplicationState statusLeaving(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).leaving(tokens));
+ }
+
+ public static VersionedApplicationState statusWithPortLeaving(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS_WITH_PORT, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).leaving(tokens));
+ }
+
+ public static VersionedValue toVersionedValue(VersionedApplicationState vv)
+ {
+ return VersionedValue.unsafeMakeVersionedValue(vv.value, vv.version);
+ }
+
+ public static ApplicationState toApplicationState(VersionedApplicationState vv)
+ {
+ return ApplicationState.values()[vv.applicationState];
+ }
+
+ public static VersionedApplicationState unsafeVersionedToken(IInvokableInstance instance,
+ ApplicationState applicationState,
+ SerializableBiFunction<IPartitioner, Collection<Token>, VersionedValue> supplier,
+ String partitionerStr, String initialTokenStr)
+ {
+ return instance.appliesOnInstance((String partitionerString, String tokenString) -> {
+ IPartitioner partitioner = FBUtilities.newPartitioner(partitionerString);
+ Token token = partitioner.getTokenFactory().fromString(tokenString);
+
+ VersionedValue versionedValue = supplier.apply(partitioner, Collections.singleton(token));
+ return new VersionedApplicationState(applicationState.ordinal(), versionedValue.value, versionedValue.version);
+ }).apply(partitionerStr, initialTokenStr);
+ }
+
+ public static VersionedApplicationState versionedToken(IInvokableInstance instance, ApplicationState applicationState, SerializableBiFunction<IPartitioner, Collection<Token>, VersionedValue> supplier)
+ {
+ return unsafeVersionedToken(instance, applicationState, supplier, instance.config().getString("partitioner"), instance.config().getString("initial_token"));
+ }
+
+ public void removeFromRing(IInstance peer)
+ {
+ InetAddressAndPort endpoint = toCassandraInetAddressAndPort(peer.broadcastAddress());
+
+ TokenMetadata tokenMetadata = StorageService.instance.getTokenMetadata();
+ tokenMetadata.removeEndpoint(endpoint);
+ Collection<Token> tokens = tokenMetadata.getTokens(endpoint);
+ if (!tokens.isEmpty())
+ tokenMetadata.removeBootstrapTokens(tokens);
+
+ Gossiper.runInGossipStageBlocking(() -> Gossiper.instance.unsafeAnulEndpoint(endpoint));
+
+ SystemKeyspace.removeEndpoint(endpoint);
+ PendingRangeCalculatorService.instance.update();
+ PendingRangeCalculatorService.instance.blockUntilFinished();
+ }
+
+ public static void changeGossipState(Stream<IInvokableInstance> targets, Instance peer, List<VersionedApplicationState> newState)
+ {
+ targets.forEach((instance) -> {
+ changeGossipState(instance, peer, newState);
+ });
+ }
+
+ /**
+ * Changes gossip state of the `peer` on `target`
+ */
+ public static void changeGossipState(IInvokableInstance target, IInstance peer, List<VersionedApplicationState> newState)
+ {
+ int version = peer.isShutdown() ? MessagingService.current_version : peer.getMessagingVersion();
+
+ target.appliesOnInstance((InetSocketAddress addr, UUID hostId, Integer messagingVersion) -> {
+ InetAddressAndPort endpoint = toCassandraInetAddressAndPort(addr);
+ StorageService storageService = StorageService.instance;
+
+ Gossiper.runInGossipStageBlocking(() -> {
+ EndpointState state = Gossiper.instance.getEndpointStateForEndpoint(endpoint);
+ if (state == null)
+ {
+ Gossiper.instance.initializeNodeUnsafe(endpoint, hostId, 1);
Review comment:
for safety can we remove the state? This is a public function with variable input, so nothing forces the input to include NET_VERSION
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
[GitHub] [cassandra] dcapwell commented on a change in pull request #759: Improve machinery for testing bootstrap and range movements
Posted by GitBox <gi...@apache.org>.
dcapwell commented on a change in pull request #759:
URL: https://github.com/apache/cassandra/pull/759#discussion_r508850214
##########
File path: test/distributed/org/apache/cassandra/distributed/action/GossipHelper.java
##########
@@ -0,0 +1,431 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.distributed.action;
+
+import java.io.IOException;
+import java.io.Serializable;
+import java.net.InetSocketAddress;
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.TimeUnit;
+import java.util.stream.Stream;
+
+import net.openhft.chronicle.core.util.SerializableBiFunction;
+import org.apache.cassandra.db.SystemKeyspace;
+import org.apache.cassandra.dht.IPartitioner;
+import org.apache.cassandra.dht.Token;
+import org.apache.cassandra.distributed.api.IInstance;
+import org.apache.cassandra.distributed.api.IInvokableInstance;
+import org.apache.cassandra.distributed.api.IIsolatedExecutor;
+import org.apache.cassandra.distributed.impl.Instance;
+import org.apache.cassandra.distributed.shared.VersionedApplicationState;
+import org.apache.cassandra.gms.ApplicationState;
+import org.apache.cassandra.gms.EndpointState;
+import org.apache.cassandra.gms.Gossiper;
+import org.apache.cassandra.gms.VersionedValue;
+import org.apache.cassandra.io.util.DataInputBuffer;
+import org.apache.cassandra.io.util.DataOutputBuffer;
+import org.apache.cassandra.locator.InetAddressAndPort;
+import org.apache.cassandra.locator.TokenMetadata;
+import org.apache.cassandra.net.MessagingService;
+import org.apache.cassandra.schema.MigrationManager;
+import org.apache.cassandra.service.PendingRangeCalculatorService;
+import org.apache.cassandra.service.StorageService;
+import org.apache.cassandra.utils.FBUtilities;
+
+import static org.apache.cassandra.distributed.impl.DistributedTestSnitch.toCassandraInetAddressAndPort;
+
+public class GossipHelper
+{
+ public static InstanceAction statusToBootstrap(IInvokableInstance newNode)
+ {
+ return (instance) ->
+ {
+ changeGossipState(instance,
+ newNode,
+ Arrays.asList(tokens(newNode),
+ statusBootstrapping(newNode),
+ statusWithPortBootstrapping(newNode)));
+ };
+ }
+
+ public static InstanceAction statusToNormal(IInvokableInstance peer)
+ {
+ return (target) ->
+ {
+ changeGossipState(target,
+ peer,
+ Arrays.asList(tokens(peer),
+ statusNormal(peer),
+ releaseVersion(peer),
+ statusWithPortNormal(peer)));
+ };
+ }
+
+ /**
+ * This method is unsafe and should be used _only_ when gossip is not used or available: it creates versioned values on the
+ * target instance, which means Gossip versioning gets out of sync. Use a safe couterpart at all times when performing _any_
+ * ring movement operations _or_ if Gossip is used.
+ */
+ public static InstanceAction unsafeStatusToNormal(IInstance peer)
+ {
+ return (target) ->
+ {
+ changeGossipState(target,
+ peer,
+ Arrays.asList(unsafeVersionedToken(target,
+ ApplicationState.TOKENS,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).tokens(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeVersionedToken(target,
+ ApplicationState.STATUS,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeVersionedToken(target,
+ ApplicationState.STATUS_WITH_PORT,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeReleaseVersion(target,
+ peer.config().getString("partitioner"),
+ peer.getReleaseVersionString())));
+ };
+ }
+
+ public static InstanceAction statusToLeaving(IInvokableInstance newNode)
+ {
+ return (instance) -> {
+ changeGossipState(instance,
+ newNode,
+ Arrays.asList(tokens(newNode),
+ statusLeaving(newNode),
+ statusWithPortLeaving(newNode)));
+ };
+ }
+
+ public static InstanceAction bootstrap()
+ {
+ return new BootstrapAction();
+ }
+
+ public static InstanceAction bootstrap(boolean joinRing, Duration waitForBootstrap, Duration waitForSchema)
+ {
+ return new BootstrapAction(joinRing, waitForBootstrap, waitForSchema);
+ }
+
+ public static InstanceAction disseminateGossipState(IInvokableInstance newNode)
+ {
+ return new DisseminateGossipState(newNode);
+ }
+
+ public static InstanceAction pullSchemaFrom(IInvokableInstance pullFrom)
+ {
+ return new PullSchemaFrom(pullFrom);
+ }
+
+ private static InstanceAction disableBinary()
+ {
+ return (instance) -> {
+ instance.runOnInstance(StorageService.instance::stopNativeTransport);
+ };
+ }
+
+ private static class DisseminateGossipState implements InstanceAction
+ {
+ final Map<InetSocketAddress, byte[]> gossipState;
+
+ public DisseminateGossipState(IInvokableInstance... from)
+ {
+ gossipState = new HashMap<>();
+ for (IInvokableInstance node : from)
+ {
+ byte[] epBytes = node.callsOnInstance(() -> {
+ EndpointState epState = Gossiper.instance.getEndpointStateForEndpoint(FBUtilities.getBroadcastAddressAndPort());
+ return toBytes(epState);
+ }).call();
+ gossipState.put(node.broadcastAddress(), epBytes);
+ }
+ }
+
+ public void accept(IInvokableInstance instance)
+ {
+ instance.appliesOnInstance((IIsolatedExecutor.SerializableFunction<Map<InetSocketAddress, byte[]>, Void>)
+ (map) -> {
+ Map<InetAddressAndPort, EndpointState> newState = new HashMap<>();
+ for (Map.Entry<InetSocketAddress, byte[]> e : map.entrySet())
+ newState.put(toCassandraInetAddressAndPort(e.getKey()), fromBytes(e.getValue()));
+
+ Gossiper.runInGossipStageBlocking(() -> {
+ Gossiper.instance.applyStateLocally(newState);
+ });
+ return null;
+ }).apply(gossipState);
+ }
+ }
+
+ public static byte[] toBytes(EndpointState epState)
+ {
+ try (DataOutputBuffer out = new DataOutputBuffer(1024))
+ {
+ EndpointState.serializer.serialize(epState, out, MessagingService.current_version);
+ return out.toByteArray();
+ }
+ catch (IOException e)
+ {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public static EndpointState fromBytes(byte[] bytes)
+ {
+ try (DataInputBuffer in = new DataInputBuffer(bytes))
+ {
+ return EndpointState.serializer.deserialize(in, MessagingService.current_version);
+ }
+ catch (Throwable t)
+ {
+ throw new RuntimeException(t);
+ }
+ }
+
+ private static class PullSchemaFrom implements InstanceAction
+ {
+ final InetSocketAddress pullFrom;
+
+ public PullSchemaFrom(IInvokableInstance pullFrom)
+ {
+ this.pullFrom = pullFrom.broadcastAddress();;
+ }
+
+ public void accept(IInvokableInstance pullTo)
+ {
+ pullTo.acceptsOnInstance((InetSocketAddress pullFrom) -> {
+ InetAddressAndPort endpoint = toCassandraInetAddressAndPort(pullFrom);
+ EndpointState state = Gossiper.instance.getEndpointStateForEndpoint(endpoint);
+ MigrationManager.scheduleSchemaPull(endpoint, state);
+ MigrationManager.waitUntilReadyForBootstrap();
+ }).accept(pullFrom);
+ }
+ }
+
+ private static class BootstrapAction implements InstanceAction, Serializable
+ {
+ private final boolean joinRing;
+ private final Duration waitForBootstrap;
+ private final Duration waitForSchema;
+
+ public BootstrapAction()
+ {
+ this(true, Duration.ofMinutes(10), Duration.ofSeconds(10));
+ }
+
+ public BootstrapAction(boolean joinRing, Duration waitForBootstrap, Duration waitForSchema)
+ {
+ this.joinRing = joinRing;
+ this.waitForBootstrap = waitForBootstrap;
+ this.waitForSchema = waitForSchema;
+ }
+
+ public void accept(IInvokableInstance instance)
+ {
+ instance.appliesOnInstance((String partitionerString, String tokenString) -> {
Review comment:
spoke in slack, this is the last remaining comment. Alex asked for the day to replay to this so we will sync up tomorrow about this.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
[GitHub] [cassandra] ifesdjeen commented on a change in pull request #759: Improve machinery for testing bootstrap and range movements
Posted by GitBox <gi...@apache.org>.
ifesdjeen commented on a change in pull request #759:
URL: https://github.com/apache/cassandra/pull/759#discussion_r507831064
##########
File path: test/distributed/org/apache/cassandra/distributed/impl/AbstractCluster.java
##########
@@ -448,6 +444,33 @@ public int size()
i.config().localRack().equals(rackName));
}
+ public void run(Consumer<? super I> action, Predicate<I> filter) {
+ run(Collections.singletonList(action), filter);
+ }
+
+ public void run(Collection<Consumer<? super I>> actions, Predicate<I> filter) {
+ stream().forEach(instance -> {
+ for (Consumer<? super I> action : actions)
+ {
+ if (filter.test(instance))
+ action.accept(instance);
+ }
+
+ });
+ }
+
+ public void run(Consumer<? super I> action, int... instanceIds) {
+ run(Collections.singletonList(action), instanceIds);
+ }
+
+ public void run(List<Consumer<? super I>> actions, int... instanceIds) {
Review comment:
👍
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
[GitHub] [cassandra] dcapwell commented on a change in pull request #759: Improve machinery for testing bootstrap and range movements
Posted by GitBox <gi...@apache.org>.
dcapwell commented on a change in pull request #759:
URL: https://github.com/apache/cassandra/pull/759#discussion_r504185118
##########
File path: test/distributed/org/apache/cassandra/distributed/action/GossipHelper.java
##########
@@ -0,0 +1,464 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.distributed.action;
+
+
+import java.io.IOException;
+import java.net.InetSocketAddress;
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.TimeUnit;
+import java.util.function.Predicate;
+import java.util.stream.Stream;
+
+import net.openhft.chronicle.core.util.SerializableBiFunction;
+import net.openhft.chronicle.core.util.SerializableConsumer;
+import org.apache.cassandra.db.SystemKeyspace;
+import org.apache.cassandra.dht.IPartitioner;
+import org.apache.cassandra.dht.Token;
+import org.apache.cassandra.distributed.api.ICluster;
+import org.apache.cassandra.distributed.api.IInstance;
+import org.apache.cassandra.distributed.api.IInvokableInstance;
+import org.apache.cassandra.distributed.api.IIsolatedExecutor;
+import org.apache.cassandra.distributed.impl.Instance;
+import org.apache.cassandra.distributed.shared.VersionedApplicationState;
+import org.apache.cassandra.gms.ApplicationState;
+import org.apache.cassandra.gms.EndpointState;
+import org.apache.cassandra.gms.Gossiper;
+import org.apache.cassandra.gms.VersionedValue;
+import org.apache.cassandra.io.util.DataInputBuffer;
+import org.apache.cassandra.io.util.DataOutputBuffer;
+import org.apache.cassandra.locator.InetAddressAndPort;
+import org.apache.cassandra.locator.TokenMetadata;
+import org.apache.cassandra.net.MessagingService;
+import org.apache.cassandra.schema.MigrationManager;
+import org.apache.cassandra.service.PendingRangeCalculatorService;
+import org.apache.cassandra.service.StorageService;
+import org.apache.cassandra.utils.FBUtilities;
+
+import static org.apache.cassandra.distributed.impl.DistributedTestSnitch.toCassandraInetAddressAndPort;
+
+
+public class GossipHelper
+{
+
+ public static ClusterAction clusterAction(InstanceAction action)
Review comment:
Spoke in slack, I took a stab at removing the interface in favor of functions; branch = https://github.com/dcapwell/cassandra/tree/CASSANDRA-15935-range-movement-improvements, commit = https://github.com/dcapwell/cassandra/commit/ca34aee9ed43a71e26c92f09f6c6e99204816821
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
[GitHub] [cassandra] dcapwell commented on a change in pull request #759: Improve machinery for testing bootstrap and range movements
Posted by GitBox <gi...@apache.org>.
dcapwell commented on a change in pull request #759:
URL: https://github.com/apache/cassandra/pull/759#discussion_r507997952
##########
File path: test/distributed/org/apache/cassandra/distributed/action/GossipHelper.java
##########
@@ -0,0 +1,431 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.distributed.action;
+
+import java.io.IOException;
+import java.io.Serializable;
+import java.net.InetSocketAddress;
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.TimeUnit;
+import java.util.stream.Stream;
+
+import net.openhft.chronicle.core.util.SerializableBiFunction;
+import org.apache.cassandra.db.SystemKeyspace;
+import org.apache.cassandra.dht.IPartitioner;
+import org.apache.cassandra.dht.Token;
+import org.apache.cassandra.distributed.api.IInstance;
+import org.apache.cassandra.distributed.api.IInvokableInstance;
+import org.apache.cassandra.distributed.api.IIsolatedExecutor;
+import org.apache.cassandra.distributed.impl.Instance;
+import org.apache.cassandra.distributed.shared.VersionedApplicationState;
+import org.apache.cassandra.gms.ApplicationState;
+import org.apache.cassandra.gms.EndpointState;
+import org.apache.cassandra.gms.Gossiper;
+import org.apache.cassandra.gms.VersionedValue;
+import org.apache.cassandra.io.util.DataInputBuffer;
+import org.apache.cassandra.io.util.DataOutputBuffer;
+import org.apache.cassandra.locator.InetAddressAndPort;
+import org.apache.cassandra.locator.TokenMetadata;
+import org.apache.cassandra.net.MessagingService;
+import org.apache.cassandra.schema.MigrationManager;
+import org.apache.cassandra.service.PendingRangeCalculatorService;
+import org.apache.cassandra.service.StorageService;
+import org.apache.cassandra.utils.FBUtilities;
+
+import static org.apache.cassandra.distributed.impl.DistributedTestSnitch.toCassandraInetAddressAndPort;
+
+public class GossipHelper
+{
+ public static InstanceAction statusToBootstrap(IInvokableInstance newNode)
+ {
+ return (instance) ->
+ {
+ changeGossipState(instance,
+ newNode,
+ Arrays.asList(tokens(newNode),
+ statusBootstrapping(newNode),
+ statusWithPortBootstrapping(newNode)));
+ };
+ }
+
+ public static InstanceAction statusToNormal(IInvokableInstance peer)
+ {
+ return (target) ->
+ {
+ changeGossipState(target,
+ peer,
+ Arrays.asList(tokens(peer),
+ statusNormal(peer),
+ releaseVersion(peer),
+ statusWithPortNormal(peer)));
+ };
+ }
+
+ /**
+ * This method is unsafe and should be used _only_ when gossip is not used or available: it creates versioned values on the
+ * target instance, which means Gossip versioning gets out of sync. Use a safe couterpart at all times when performing _any_
+ * ring movement operations _or_ if Gossip is used.
+ */
+ public static InstanceAction unsafeStatusToNormal(IInstance peer)
+ {
+ return (target) ->
+ {
+ changeGossipState(target,
+ peer,
+ Arrays.asList(unsafeVersionedToken(target,
+ ApplicationState.TOKENS,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).tokens(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeVersionedToken(target,
+ ApplicationState.STATUS,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeVersionedToken(target,
+ ApplicationState.STATUS_WITH_PORT,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeReleaseVersion(target,
+ peer.config().getString("partitioner"),
+ peer.getReleaseVersionString())));
+ };
+ }
+
+ public static InstanceAction statusToLeaving(IInvokableInstance newNode)
+ {
+ return (instance) -> {
+ changeGossipState(instance,
+ newNode,
+ Arrays.asList(tokens(newNode),
+ statusLeaving(newNode),
+ statusWithPortLeaving(newNode)));
+ };
+ }
+
+ public static InstanceAction bootstrap()
+ {
+ return new BootstrapAction();
+ }
+
+ public static InstanceAction bootstrap(boolean joinRing, Duration waitForBootstrap, Duration waitForSchema)
+ {
+ return new BootstrapAction(joinRing, waitForBootstrap, waitForSchema);
+ }
+
+ public static InstanceAction disseminateGossipState(IInvokableInstance newNode)
+ {
+ return new DisseminateGossipState(newNode);
+ }
+
+ public static InstanceAction pullSchemaFrom(IInvokableInstance pullFrom)
+ {
+ return new PullSchemaFrom(pullFrom);
+ }
+
+ private static InstanceAction disableBinary()
+ {
+ return (instance) -> {
Review comment:
any reason to not go through nodetool? `instance.nodetool("disablebinary")`. Going through nodetool means this logic works for every branch
##########
File path: test/distributed/org/apache/cassandra/distributed/action/GossipHelper.java
##########
@@ -0,0 +1,431 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.distributed.action;
+
+import java.io.IOException;
+import java.io.Serializable;
+import java.net.InetSocketAddress;
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.TimeUnit;
+import java.util.stream.Stream;
+
+import net.openhft.chronicle.core.util.SerializableBiFunction;
+import org.apache.cassandra.db.SystemKeyspace;
+import org.apache.cassandra.dht.IPartitioner;
+import org.apache.cassandra.dht.Token;
+import org.apache.cassandra.distributed.api.IInstance;
+import org.apache.cassandra.distributed.api.IInvokableInstance;
+import org.apache.cassandra.distributed.api.IIsolatedExecutor;
+import org.apache.cassandra.distributed.impl.Instance;
+import org.apache.cassandra.distributed.shared.VersionedApplicationState;
+import org.apache.cassandra.gms.ApplicationState;
+import org.apache.cassandra.gms.EndpointState;
+import org.apache.cassandra.gms.Gossiper;
+import org.apache.cassandra.gms.VersionedValue;
+import org.apache.cassandra.io.util.DataInputBuffer;
+import org.apache.cassandra.io.util.DataOutputBuffer;
+import org.apache.cassandra.locator.InetAddressAndPort;
+import org.apache.cassandra.locator.TokenMetadata;
+import org.apache.cassandra.net.MessagingService;
+import org.apache.cassandra.schema.MigrationManager;
+import org.apache.cassandra.service.PendingRangeCalculatorService;
+import org.apache.cassandra.service.StorageService;
+import org.apache.cassandra.utils.FBUtilities;
+
+import static org.apache.cassandra.distributed.impl.DistributedTestSnitch.toCassandraInetAddressAndPort;
+
+public class GossipHelper
+{
+ public static InstanceAction statusToBootstrap(IInvokableInstance newNode)
+ {
+ return (instance) ->
+ {
+ changeGossipState(instance,
+ newNode,
+ Arrays.asList(tokens(newNode),
+ statusBootstrapping(newNode),
+ statusWithPortBootstrapping(newNode)));
+ };
+ }
+
+ public static InstanceAction statusToNormal(IInvokableInstance peer)
+ {
+ return (target) ->
+ {
+ changeGossipState(target,
+ peer,
+ Arrays.asList(tokens(peer),
+ statusNormal(peer),
+ releaseVersion(peer),
+ statusWithPortNormal(peer)));
+ };
+ }
+
+ /**
+ * This method is unsafe and should be used _only_ when gossip is not used or available: it creates versioned values on the
+ * target instance, which means Gossip versioning gets out of sync. Use a safe couterpart at all times when performing _any_
+ * ring movement operations _or_ if Gossip is used.
+ */
+ public static InstanceAction unsafeStatusToNormal(IInstance peer)
+ {
+ return (target) ->
+ {
+ changeGossipState(target,
+ peer,
+ Arrays.asList(unsafeVersionedToken(target,
+ ApplicationState.TOKENS,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).tokens(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeVersionedToken(target,
+ ApplicationState.STATUS,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeVersionedToken(target,
+ ApplicationState.STATUS_WITH_PORT,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeReleaseVersion(target,
+ peer.config().getString("partitioner"),
+ peer.getReleaseVersionString())));
+ };
+ }
+
+ public static InstanceAction statusToLeaving(IInvokableInstance newNode)
+ {
+ return (instance) -> {
+ changeGossipState(instance,
+ newNode,
+ Arrays.asList(tokens(newNode),
+ statusLeaving(newNode),
+ statusWithPortLeaving(newNode)));
+ };
+ }
+
+ public static InstanceAction bootstrap()
+ {
+ return new BootstrapAction();
+ }
+
+ public static InstanceAction bootstrap(boolean joinRing, Duration waitForBootstrap, Duration waitForSchema)
+ {
+ return new BootstrapAction(joinRing, waitForBootstrap, waitForSchema);
+ }
+
+ public static InstanceAction disseminateGossipState(IInvokableInstance newNode)
+ {
+ return new DisseminateGossipState(newNode);
+ }
+
+ public static InstanceAction pullSchemaFrom(IInvokableInstance pullFrom)
+ {
+ return new PullSchemaFrom(pullFrom);
+ }
+
+ private static InstanceAction disableBinary()
+ {
+ return (instance) -> {
+ instance.runOnInstance(StorageService.instance::stopNativeTransport);
+ };
+ }
+
+ private static class DisseminateGossipState implements InstanceAction
+ {
+ final Map<InetSocketAddress, byte[]> gossipState;
+
+ public DisseminateGossipState(IInvokableInstance... from)
+ {
+ gossipState = new HashMap<>();
+ for (IInvokableInstance node : from)
+ {
+ byte[] epBytes = node.callsOnInstance(() -> {
+ EndpointState epState = Gossiper.instance.getEndpointStateForEndpoint(FBUtilities.getBroadcastAddressAndPort());
Review comment:
if not joined the ring this should be null, should we handle the null case?
##########
File path: test/distributed/org/apache/cassandra/distributed/action/GossipHelper.java
##########
@@ -0,0 +1,431 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.distributed.action;
+
+import java.io.IOException;
+import java.io.Serializable;
+import java.net.InetSocketAddress;
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.TimeUnit;
+import java.util.stream.Stream;
+
+import net.openhft.chronicle.core.util.SerializableBiFunction;
+import org.apache.cassandra.db.SystemKeyspace;
+import org.apache.cassandra.dht.IPartitioner;
+import org.apache.cassandra.dht.Token;
+import org.apache.cassandra.distributed.api.IInstance;
+import org.apache.cassandra.distributed.api.IInvokableInstance;
+import org.apache.cassandra.distributed.api.IIsolatedExecutor;
+import org.apache.cassandra.distributed.impl.Instance;
+import org.apache.cassandra.distributed.shared.VersionedApplicationState;
+import org.apache.cassandra.gms.ApplicationState;
+import org.apache.cassandra.gms.EndpointState;
+import org.apache.cassandra.gms.Gossiper;
+import org.apache.cassandra.gms.VersionedValue;
+import org.apache.cassandra.io.util.DataInputBuffer;
+import org.apache.cassandra.io.util.DataOutputBuffer;
+import org.apache.cassandra.locator.InetAddressAndPort;
+import org.apache.cassandra.locator.TokenMetadata;
+import org.apache.cassandra.net.MessagingService;
+import org.apache.cassandra.schema.MigrationManager;
+import org.apache.cassandra.service.PendingRangeCalculatorService;
+import org.apache.cassandra.service.StorageService;
+import org.apache.cassandra.utils.FBUtilities;
+
+import static org.apache.cassandra.distributed.impl.DistributedTestSnitch.toCassandraInetAddressAndPort;
+
+public class GossipHelper
+{
+ public static InstanceAction statusToBootstrap(IInvokableInstance newNode)
+ {
+ return (instance) ->
+ {
+ changeGossipState(instance,
+ newNode,
+ Arrays.asList(tokens(newNode),
+ statusBootstrapping(newNode),
+ statusWithPortBootstrapping(newNode)));
+ };
+ }
+
+ public static InstanceAction statusToNormal(IInvokableInstance peer)
+ {
+ return (target) ->
+ {
+ changeGossipState(target,
+ peer,
+ Arrays.asList(tokens(peer),
+ statusNormal(peer),
+ releaseVersion(peer),
+ statusWithPortNormal(peer)));
+ };
+ }
+
+ /**
+ * This method is unsafe and should be used _only_ when gossip is not used or available: it creates versioned values on the
+ * target instance, which means Gossip versioning gets out of sync. Use a safe couterpart at all times when performing _any_
+ * ring movement operations _or_ if Gossip is used.
+ */
+ public static InstanceAction unsafeStatusToNormal(IInstance peer)
+ {
+ return (target) ->
+ {
+ changeGossipState(target,
+ peer,
+ Arrays.asList(unsafeVersionedToken(target,
+ ApplicationState.TOKENS,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).tokens(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeVersionedToken(target,
+ ApplicationState.STATUS,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeVersionedToken(target,
+ ApplicationState.STATUS_WITH_PORT,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeReleaseVersion(target,
+ peer.config().getString("partitioner"),
+ peer.getReleaseVersionString())));
+ };
+ }
+
+ public static InstanceAction statusToLeaving(IInvokableInstance newNode)
+ {
+ return (instance) -> {
+ changeGossipState(instance,
+ newNode,
+ Arrays.asList(tokens(newNode),
+ statusLeaving(newNode),
+ statusWithPortLeaving(newNode)));
+ };
+ }
+
+ public static InstanceAction bootstrap()
+ {
+ return new BootstrapAction();
+ }
+
+ public static InstanceAction bootstrap(boolean joinRing, Duration waitForBootstrap, Duration waitForSchema)
+ {
+ return new BootstrapAction(joinRing, waitForBootstrap, waitForSchema);
+ }
+
+ public static InstanceAction disseminateGossipState(IInvokableInstance newNode)
+ {
+ return new DisseminateGossipState(newNode);
+ }
+
+ public static InstanceAction pullSchemaFrom(IInvokableInstance pullFrom)
+ {
+ return new PullSchemaFrom(pullFrom);
+ }
+
+ private static InstanceAction disableBinary()
+ {
+ return (instance) -> {
+ instance.runOnInstance(StorageService.instance::stopNativeTransport);
+ };
+ }
+
+ private static class DisseminateGossipState implements InstanceAction
+ {
+ final Map<InetSocketAddress, byte[]> gossipState;
+
+ public DisseminateGossipState(IInvokableInstance... from)
+ {
+ gossipState = new HashMap<>();
+ for (IInvokableInstance node : from)
+ {
+ byte[] epBytes = node.callsOnInstance(() -> {
+ EndpointState epState = Gossiper.instance.getEndpointStateForEndpoint(FBUtilities.getBroadcastAddressAndPort());
+ return toBytes(epState);
+ }).call();
+ gossipState.put(node.broadcastAddress(), epBytes);
+ }
+ }
+
+ public void accept(IInvokableInstance instance)
+ {
+ instance.appliesOnInstance((IIsolatedExecutor.SerializableFunction<Map<InetSocketAddress, byte[]>, Void>)
+ (map) -> {
+ Map<InetAddressAndPort, EndpointState> newState = new HashMap<>();
+ for (Map.Entry<InetSocketAddress, byte[]> e : map.entrySet())
+ newState.put(toCassandraInetAddressAndPort(e.getKey()), fromBytes(e.getValue()));
+
+ Gossiper.runInGossipStageBlocking(() -> {
+ Gossiper.instance.applyStateLocally(newState);
+ });
+ return null;
+ }).apply(gossipState);
+ }
+ }
+
+ public static byte[] toBytes(EndpointState epState)
+ {
+ try (DataOutputBuffer out = new DataOutputBuffer(1024))
+ {
+ EndpointState.serializer.serialize(epState, out, MessagingService.current_version);
+ return out.toByteArray();
+ }
+ catch (IOException e)
+ {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public static EndpointState fromBytes(byte[] bytes)
+ {
+ try (DataInputBuffer in = new DataInputBuffer(bytes))
+ {
+ return EndpointState.serializer.deserialize(in, MessagingService.current_version);
+ }
+ catch (Throwable t)
+ {
+ throw new RuntimeException(t);
+ }
+ }
+
+ private static class PullSchemaFrom implements InstanceAction
+ {
+ final InetSocketAddress pullFrom;
+
+ public PullSchemaFrom(IInvokableInstance pullFrom)
+ {
+ this.pullFrom = pullFrom.broadcastAddress();;
+ }
+
+ public void accept(IInvokableInstance pullTo)
+ {
+ pullTo.acceptsOnInstance((InetSocketAddress pullFrom) -> {
+ InetAddressAndPort endpoint = toCassandraInetAddressAndPort(pullFrom);
+ EndpointState state = Gossiper.instance.getEndpointStateForEndpoint(endpoint);
+ MigrationManager.scheduleSchemaPull(endpoint, state);
+ MigrationManager.waitUntilReadyForBootstrap();
+ }).accept(pullFrom);
+ }
+ }
+
+ private static class BootstrapAction implements InstanceAction, Serializable
+ {
+ private final boolean joinRing;
+ private final Duration waitForBootstrap;
+ private final Duration waitForSchema;
+
+ public BootstrapAction()
+ {
+ this(true, Duration.ofMinutes(10), Duration.ofSeconds(10));
+ }
+
+ public BootstrapAction(boolean joinRing, Duration waitForBootstrap, Duration waitForSchema)
+ {
+ this.joinRing = joinRing;
+ this.waitForBootstrap = waitForBootstrap;
+ this.waitForSchema = waitForSchema;
+ }
+
+ public void accept(IInvokableInstance instance)
+ {
+ instance.appliesOnInstance((String partitionerString, String tokenString) -> {
+ IPartitioner partitioner = FBUtilities.newPartitioner(partitionerString);
+ List<Token> tokens = Collections.singletonList(partitioner.getTokenFactory().fromString(tokenString));
+ try
+ {
+ SystemKeyspace.setBootstrapState(SystemKeyspace.BootstrapState.IN_PROGRESS);
+ StorageService.instance.waitForSchema((int) waitForSchema.toMillis());
Review comment:
`org.apache.cassandra.service.StorageService#waitForSchema` isn't time based, its loop based; see https://github.com/apache/cassandra/blob/trunk/src/java/org/apache/cassandra/service/StorageService.java#L853-L874
since each attempt is a 1s sleep, the default wait is 10,000 attempts or 2h46m40s.
This feels like a bug since this is called in `org.apache.cassandra.service.StorageService#joinTokenRing` and uses the ring delay, so 30,000 attempts or 8h20m.
Given your logic mostly matches the join ring logic, I am fine with this code (please use `Math.toIntExact` to make sure we don't produce a negative, `Math.toIntExact(waitForSchema.toMillis())`), but can we figure out why this method is loop based and not time based, and resolve it (fix usage or fix this method)?
##########
File path: test/distributed/org/apache/cassandra/distributed/action/GossipHelper.java
##########
@@ -0,0 +1,431 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.distributed.action;
+
+import java.io.IOException;
+import java.io.Serializable;
+import java.net.InetSocketAddress;
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.TimeUnit;
+import java.util.stream.Stream;
+
+import net.openhft.chronicle.core.util.SerializableBiFunction;
+import org.apache.cassandra.db.SystemKeyspace;
+import org.apache.cassandra.dht.IPartitioner;
+import org.apache.cassandra.dht.Token;
+import org.apache.cassandra.distributed.api.IInstance;
+import org.apache.cassandra.distributed.api.IInvokableInstance;
+import org.apache.cassandra.distributed.api.IIsolatedExecutor;
+import org.apache.cassandra.distributed.impl.Instance;
+import org.apache.cassandra.distributed.shared.VersionedApplicationState;
+import org.apache.cassandra.gms.ApplicationState;
+import org.apache.cassandra.gms.EndpointState;
+import org.apache.cassandra.gms.Gossiper;
+import org.apache.cassandra.gms.VersionedValue;
+import org.apache.cassandra.io.util.DataInputBuffer;
+import org.apache.cassandra.io.util.DataOutputBuffer;
+import org.apache.cassandra.locator.InetAddressAndPort;
+import org.apache.cassandra.locator.TokenMetadata;
+import org.apache.cassandra.net.MessagingService;
+import org.apache.cassandra.schema.MigrationManager;
+import org.apache.cassandra.service.PendingRangeCalculatorService;
+import org.apache.cassandra.service.StorageService;
+import org.apache.cassandra.utils.FBUtilities;
+
+import static org.apache.cassandra.distributed.impl.DistributedTestSnitch.toCassandraInetAddressAndPort;
+
+public class GossipHelper
+{
+ public static InstanceAction statusToBootstrap(IInvokableInstance newNode)
+ {
+ return (instance) ->
+ {
+ changeGossipState(instance,
+ newNode,
+ Arrays.asList(tokens(newNode),
+ statusBootstrapping(newNode),
+ statusWithPortBootstrapping(newNode)));
+ };
+ }
+
+ public static InstanceAction statusToNormal(IInvokableInstance peer)
+ {
+ return (target) ->
+ {
+ changeGossipState(target,
+ peer,
+ Arrays.asList(tokens(peer),
+ statusNormal(peer),
+ releaseVersion(peer),
+ statusWithPortNormal(peer)));
+ };
+ }
+
+ /**
+ * This method is unsafe and should be used _only_ when gossip is not used or available: it creates versioned values on the
+ * target instance, which means Gossip versioning gets out of sync. Use a safe couterpart at all times when performing _any_
+ * ring movement operations _or_ if Gossip is used.
+ */
+ public static InstanceAction unsafeStatusToNormal(IInstance peer)
+ {
+ return (target) ->
+ {
+ changeGossipState(target,
+ peer,
+ Arrays.asList(unsafeVersionedToken(target,
+ ApplicationState.TOKENS,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).tokens(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeVersionedToken(target,
+ ApplicationState.STATUS,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeVersionedToken(target,
+ ApplicationState.STATUS_WITH_PORT,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeReleaseVersion(target,
+ peer.config().getString("partitioner"),
+ peer.getReleaseVersionString())));
+ };
+ }
+
+ public static InstanceAction statusToLeaving(IInvokableInstance newNode)
+ {
+ return (instance) -> {
+ changeGossipState(instance,
+ newNode,
+ Arrays.asList(tokens(newNode),
+ statusLeaving(newNode),
+ statusWithPortLeaving(newNode)));
+ };
+ }
+
+ public static InstanceAction bootstrap()
+ {
+ return new BootstrapAction();
+ }
+
+ public static InstanceAction bootstrap(boolean joinRing, Duration waitForBootstrap, Duration waitForSchema)
+ {
+ return new BootstrapAction(joinRing, waitForBootstrap, waitForSchema);
+ }
+
+ public static InstanceAction disseminateGossipState(IInvokableInstance newNode)
+ {
+ return new DisseminateGossipState(newNode);
+ }
+
+ public static InstanceAction pullSchemaFrom(IInvokableInstance pullFrom)
+ {
+ return new PullSchemaFrom(pullFrom);
+ }
+
+ private static InstanceAction disableBinary()
+ {
+ return (instance) -> {
+ instance.runOnInstance(StorageService.instance::stopNativeTransport);
+ };
+ }
+
+ private static class DisseminateGossipState implements InstanceAction
+ {
+ final Map<InetSocketAddress, byte[]> gossipState;
+
+ public DisseminateGossipState(IInvokableInstance... from)
+ {
+ gossipState = new HashMap<>();
+ for (IInvokableInstance node : from)
+ {
+ byte[] epBytes = node.callsOnInstance(() -> {
+ EndpointState epState = Gossiper.instance.getEndpointStateForEndpoint(FBUtilities.getBroadcastAddressAndPort());
+ return toBytes(epState);
+ }).call();
+ gossipState.put(node.broadcastAddress(), epBytes);
+ }
+ }
+
+ public void accept(IInvokableInstance instance)
+ {
+ instance.appliesOnInstance((IIsolatedExecutor.SerializableFunction<Map<InetSocketAddress, byte[]>, Void>)
+ (map) -> {
+ Map<InetAddressAndPort, EndpointState> newState = new HashMap<>();
+ for (Map.Entry<InetSocketAddress, byte[]> e : map.entrySet())
+ newState.put(toCassandraInetAddressAndPort(e.getKey()), fromBytes(e.getValue()));
+
+ Gossiper.runInGossipStageBlocking(() -> {
+ Gossiper.instance.applyStateLocally(newState);
+ });
+ return null;
+ }).apply(gossipState);
+ }
+ }
+
+ public static byte[] toBytes(EndpointState epState)
+ {
+ try (DataOutputBuffer out = new DataOutputBuffer(1024))
+ {
+ EndpointState.serializer.serialize(epState, out, MessagingService.current_version);
+ return out.toByteArray();
+ }
+ catch (IOException e)
+ {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public static EndpointState fromBytes(byte[] bytes)
+ {
+ try (DataInputBuffer in = new DataInputBuffer(bytes))
+ {
+ return EndpointState.serializer.deserialize(in, MessagingService.current_version);
+ }
+ catch (Throwable t)
+ {
+ throw new RuntimeException(t);
+ }
+ }
+
+ private static class PullSchemaFrom implements InstanceAction
+ {
+ final InetSocketAddress pullFrom;
+
+ public PullSchemaFrom(IInvokableInstance pullFrom)
+ {
+ this.pullFrom = pullFrom.broadcastAddress();;
+ }
+
+ public void accept(IInvokableInstance pullTo)
+ {
+ pullTo.acceptsOnInstance((InetSocketAddress pullFrom) -> {
+ InetAddressAndPort endpoint = toCassandraInetAddressAndPort(pullFrom);
+ EndpointState state = Gossiper.instance.getEndpointStateForEndpoint(endpoint);
+ MigrationManager.scheduleSchemaPull(endpoint, state);
+ MigrationManager.waitUntilReadyForBootstrap();
+ }).accept(pullFrom);
+ }
+ }
+
+ private static class BootstrapAction implements InstanceAction, Serializable
+ {
+ private final boolean joinRing;
+ private final Duration waitForBootstrap;
+ private final Duration waitForSchema;
+
+ public BootstrapAction()
+ {
+ this(true, Duration.ofMinutes(10), Duration.ofSeconds(10));
+ }
+
+ public BootstrapAction(boolean joinRing, Duration waitForBootstrap, Duration waitForSchema)
+ {
+ this.joinRing = joinRing;
+ this.waitForBootstrap = waitForBootstrap;
+ this.waitForSchema = waitForSchema;
+ }
+
+ public void accept(IInvokableInstance instance)
+ {
+ instance.appliesOnInstance((String partitionerString, String tokenString) -> {
+ IPartitioner partitioner = FBUtilities.newPartitioner(partitionerString);
+ List<Token> tokens = Collections.singletonList(partitioner.getTokenFactory().fromString(tokenString));
+ try
+ {
+ SystemKeyspace.setBootstrapState(SystemKeyspace.BootstrapState.IN_PROGRESS);
+ StorageService.instance.waitForSchema((int) waitForSchema.toMillis());
+ PendingRangeCalculatorService.instance.blockUntilFinished();
+ StorageService.instance.startBootstrap(tokens).get(waitForBootstrap.toMillis(), TimeUnit.MILLISECONDS);
+ StorageService.instance.setUpDistributedSystemKeyspaces();
+ if (joinRing)
+ StorageService.instance.finishJoiningRing(true, tokens);
+ }
+ catch (Throwable t)
+ {
+ throw new RuntimeException(t);
+ }
+
+ return null;
+ }).apply(instance.config().getString("partitioner"), instance.config().getString("initial_token"));
+ }
+ }
+
+ public static InstanceAction decomission()
+ {
+ return (target) -> {
+ target.runOnInstance(() -> {
+ try
+ {
+ StorageService.instance.decommission(false);
+ }
+ catch (InterruptedException e)
+ {
+ throw new RuntimeException();
+ }
+ });
+ };
+ }
+
+
+ public static VersionedApplicationState tokens(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.TOKENS, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).tokens(tokens));
+ }
+
+ public static VersionedApplicationState unsafeReleaseVersion(IInvokableInstance instance, String partitionerStr, String releaseVersionStr)
Review comment:
maybe private so users only call `releaseVersion`?
##########
File path: test/distributed/org/apache/cassandra/distributed/impl/Instance.java
##########
@@ -519,72 +524,6 @@ private Config loadConfig(IInstanceConfig overrides)
return config;
}
- private void initializeRing(ICluster cluster)
- {
- // This should be done outside instance in order to avoid serializing config
- String partitionerName = config.getString("partitioner");
- List<String> initialTokens = new ArrayList<>();
- List<InetSocketAddress> hosts = new ArrayList<>();
- List<UUID> hostIds = new ArrayList<>();
- List<String> versions = new ArrayList<>();
- for (int i = 1 ; i <= cluster.size() ; ++i)
- {
- IInstance instance = cluster.get(i);
- IInstanceConfig config = instance.config();
- initialTokens.add(config.getString("initial_token"));
- hosts.add(config.broadcastAddress());
- hostIds.add(config.hostId());
- versions.add(instance.getReleaseVersionString());
- }
-
- try
- {
- IPartitioner partitioner = FBUtilities.newPartitioner(partitionerName);
- StorageService storageService = StorageService.instance;
- List<Token> tokens = new ArrayList<>();
- for (String token : initialTokens)
- tokens.add(partitioner.getTokenFactory().fromString(token));
-
- for (int i = 0; i < tokens.size(); i++)
- {
- InetSocketAddress ep = hosts.get(i);
- InetAddressAndPort addressAndPort = toCassandraInetAddressAndPort(ep);
- UUID hostId = hostIds.get(i);
- Token token = tokens.get(i);
- String releaseVersion = versions.get(i);
- Gossiper.runInGossipStageBlocking(() -> {
- Gossiper.instance.initializeNodeUnsafe(addressAndPort, hostId, 1);
- Gossiper.instance.injectApplicationState(addressAndPort,
- ApplicationState.TOKENS,
- new VersionedValue.VersionedValueFactory(partitioner).tokens(Collections.singleton(token)));
- Gossiper.instance.injectApplicationState(addressAndPort,
- ApplicationState.RELEASE_VERSION,
- new VersionedValue.VersionedValueFactory(partitioner).releaseVersion(releaseVersion));
- storageService.onChange(addressAndPort,
- ApplicationState.STATUS_WITH_PORT,
- new VersionedValue.VersionedValueFactory(partitioner).normal(Collections.singleton(token)));
- storageService.onChange(addressAndPort,
- ApplicationState.STATUS,
- new VersionedValue.VersionedValueFactory(partitioner).normal(Collections.singleton(token)));
- Gossiper.instance.realMarkAlive(addressAndPort, Gossiper.instance.getEndpointStateForEndpoint(addressAndPort));
- });
-
- int messagingVersion = cluster.get(ep).isShutdown()
Review comment:
since we don't include `NET_VERSION` I feel that this logic should still exist here, that or update gossip to include `NET_VERSION`.
##########
File path: test/distributed/org/apache/cassandra/distributed/action/GossipHelper.java
##########
@@ -0,0 +1,431 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.distributed.action;
+
+import java.io.IOException;
+import java.io.Serializable;
+import java.net.InetSocketAddress;
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.TimeUnit;
+import java.util.stream.Stream;
+
+import net.openhft.chronicle.core.util.SerializableBiFunction;
+import org.apache.cassandra.db.SystemKeyspace;
+import org.apache.cassandra.dht.IPartitioner;
+import org.apache.cassandra.dht.Token;
+import org.apache.cassandra.distributed.api.IInstance;
+import org.apache.cassandra.distributed.api.IInvokableInstance;
+import org.apache.cassandra.distributed.api.IIsolatedExecutor;
+import org.apache.cassandra.distributed.impl.Instance;
+import org.apache.cassandra.distributed.shared.VersionedApplicationState;
+import org.apache.cassandra.gms.ApplicationState;
+import org.apache.cassandra.gms.EndpointState;
+import org.apache.cassandra.gms.Gossiper;
+import org.apache.cassandra.gms.VersionedValue;
+import org.apache.cassandra.io.util.DataInputBuffer;
+import org.apache.cassandra.io.util.DataOutputBuffer;
+import org.apache.cassandra.locator.InetAddressAndPort;
+import org.apache.cassandra.locator.TokenMetadata;
+import org.apache.cassandra.net.MessagingService;
+import org.apache.cassandra.schema.MigrationManager;
+import org.apache.cassandra.service.PendingRangeCalculatorService;
+import org.apache.cassandra.service.StorageService;
+import org.apache.cassandra.utils.FBUtilities;
+
+import static org.apache.cassandra.distributed.impl.DistributedTestSnitch.toCassandraInetAddressAndPort;
+
+public class GossipHelper
+{
+ public static InstanceAction statusToBootstrap(IInvokableInstance newNode)
+ {
+ return (instance) ->
+ {
+ changeGossipState(instance,
+ newNode,
+ Arrays.asList(tokens(newNode),
+ statusBootstrapping(newNode),
+ statusWithPortBootstrapping(newNode)));
+ };
+ }
+
+ public static InstanceAction statusToNormal(IInvokableInstance peer)
+ {
+ return (target) ->
+ {
+ changeGossipState(target,
+ peer,
+ Arrays.asList(tokens(peer),
+ statusNormal(peer),
+ releaseVersion(peer),
+ statusWithPortNormal(peer)));
+ };
+ }
+
+ /**
+ * This method is unsafe and should be used _only_ when gossip is not used or available: it creates versioned values on the
+ * target instance, which means Gossip versioning gets out of sync. Use a safe couterpart at all times when performing _any_
+ * ring movement operations _or_ if Gossip is used.
+ */
+ public static InstanceAction unsafeStatusToNormal(IInstance peer)
+ {
+ return (target) ->
+ {
+ changeGossipState(target,
+ peer,
+ Arrays.asList(unsafeVersionedToken(target,
+ ApplicationState.TOKENS,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).tokens(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeVersionedToken(target,
+ ApplicationState.STATUS,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeVersionedToken(target,
+ ApplicationState.STATUS_WITH_PORT,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeReleaseVersion(target,
+ peer.config().getString("partitioner"),
+ peer.getReleaseVersionString())));
+ };
+ }
+
+ public static InstanceAction statusToLeaving(IInvokableInstance newNode)
+ {
+ return (instance) -> {
+ changeGossipState(instance,
+ newNode,
+ Arrays.asList(tokens(newNode),
+ statusLeaving(newNode),
+ statusWithPortLeaving(newNode)));
+ };
+ }
+
+ public static InstanceAction bootstrap()
+ {
+ return new BootstrapAction();
+ }
+
+ public static InstanceAction bootstrap(boolean joinRing, Duration waitForBootstrap, Duration waitForSchema)
+ {
+ return new BootstrapAction(joinRing, waitForBootstrap, waitForSchema);
+ }
+
+ public static InstanceAction disseminateGossipState(IInvokableInstance newNode)
+ {
+ return new DisseminateGossipState(newNode);
+ }
+
+ public static InstanceAction pullSchemaFrom(IInvokableInstance pullFrom)
+ {
+ return new PullSchemaFrom(pullFrom);
+ }
+
+ private static InstanceAction disableBinary()
+ {
+ return (instance) -> {
+ instance.runOnInstance(StorageService.instance::stopNativeTransport);
+ };
+ }
+
+ private static class DisseminateGossipState implements InstanceAction
+ {
+ final Map<InetSocketAddress, byte[]> gossipState;
+
+ public DisseminateGossipState(IInvokableInstance... from)
+ {
+ gossipState = new HashMap<>();
+ for (IInvokableInstance node : from)
+ {
+ byte[] epBytes = node.callsOnInstance(() -> {
+ EndpointState epState = Gossiper.instance.getEndpointStateForEndpoint(FBUtilities.getBroadcastAddressAndPort());
+ return toBytes(epState);
+ }).call();
+ gossipState.put(node.broadcastAddress(), epBytes);
+ }
+ }
+
+ public void accept(IInvokableInstance instance)
+ {
+ instance.appliesOnInstance((IIsolatedExecutor.SerializableFunction<Map<InetSocketAddress, byte[]>, Void>)
+ (map) -> {
+ Map<InetAddressAndPort, EndpointState> newState = new HashMap<>();
+ for (Map.Entry<InetSocketAddress, byte[]> e : map.entrySet())
+ newState.put(toCassandraInetAddressAndPort(e.getKey()), fromBytes(e.getValue()));
+
+ Gossiper.runInGossipStageBlocking(() -> {
+ Gossiper.instance.applyStateLocally(newState);
+ });
+ return null;
+ }).apply(gossipState);
+ }
+ }
+
+ public static byte[] toBytes(EndpointState epState)
+ {
+ try (DataOutputBuffer out = new DataOutputBuffer(1024))
+ {
+ EndpointState.serializer.serialize(epState, out, MessagingService.current_version);
+ return out.toByteArray();
+ }
+ catch (IOException e)
+ {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public static EndpointState fromBytes(byte[] bytes)
+ {
+ try (DataInputBuffer in = new DataInputBuffer(bytes))
+ {
+ return EndpointState.serializer.deserialize(in, MessagingService.current_version);
+ }
+ catch (Throwable t)
+ {
+ throw new RuntimeException(t);
+ }
+ }
+
+ private static class PullSchemaFrom implements InstanceAction
+ {
+ final InetSocketAddress pullFrom;
+
+ public PullSchemaFrom(IInvokableInstance pullFrom)
+ {
+ this.pullFrom = pullFrom.broadcastAddress();;
+ }
+
+ public void accept(IInvokableInstance pullTo)
+ {
+ pullTo.acceptsOnInstance((InetSocketAddress pullFrom) -> {
+ InetAddressAndPort endpoint = toCassandraInetAddressAndPort(pullFrom);
+ EndpointState state = Gossiper.instance.getEndpointStateForEndpoint(endpoint);
+ MigrationManager.scheduleSchemaPull(endpoint, state);
+ MigrationManager.waitUntilReadyForBootstrap();
+ }).accept(pullFrom);
+ }
+ }
+
+ private static class BootstrapAction implements InstanceAction, Serializable
+ {
+ private final boolean joinRing;
+ private final Duration waitForBootstrap;
+ private final Duration waitForSchema;
+
+ public BootstrapAction()
+ {
+ this(true, Duration.ofMinutes(10), Duration.ofSeconds(10));
+ }
+
+ public BootstrapAction(boolean joinRing, Duration waitForBootstrap, Duration waitForSchema)
+ {
+ this.joinRing = joinRing;
+ this.waitForBootstrap = waitForBootstrap;
+ this.waitForSchema = waitForSchema;
+ }
+
+ public void accept(IInvokableInstance instance)
+ {
+ instance.appliesOnInstance((String partitionerString, String tokenString) -> {
+ IPartitioner partitioner = FBUtilities.newPartitioner(partitionerString);
+ List<Token> tokens = Collections.singletonList(partitioner.getTokenFactory().fromString(tokenString));
+ try
+ {
+ SystemKeyspace.setBootstrapState(SystemKeyspace.BootstrapState.IN_PROGRESS);
+ StorageService.instance.waitForSchema((int) waitForSchema.toMillis());
+ PendingRangeCalculatorService.instance.blockUntilFinished();
+ StorageService.instance.startBootstrap(tokens).get(waitForBootstrap.toMillis(), TimeUnit.MILLISECONDS);
+ StorageService.instance.setUpDistributedSystemKeyspaces();
+ if (joinRing)
+ StorageService.instance.finishJoiningRing(true, tokens);
+ }
+ catch (Throwable t)
+ {
+ throw new RuntimeException(t);
+ }
+
+ return null;
+ }).apply(instance.config().getString("partitioner"), instance.config().getString("initial_token"));
+ }
+ }
+
+ public static InstanceAction decomission()
+ {
+ return (target) -> {
+ target.runOnInstance(() -> {
+ try
+ {
+ StorageService.instance.decommission(false);
+ }
+ catch (InterruptedException e)
+ {
+ throw new RuntimeException();
+ }
+ });
+ };
+ }
+
+
+ public static VersionedApplicationState tokens(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.TOKENS, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).tokens(tokens));
+ }
+
+ public static VersionedApplicationState unsafeReleaseVersion(IInvokableInstance instance, String partitionerStr, String releaseVersionStr)
+ {
+ return instance.appliesOnInstance((String partitionerString, String releaseVersion) -> {
+ IPartitioner partitioner = FBUtilities.newPartitioner(partitionerString);
+ VersionedValue versionedValue = new VersionedValue.VersionedValueFactory(partitioner).releaseVersion(releaseVersion);
+ return new VersionedApplicationState(ApplicationState.RELEASE_VERSION.ordinal(), versionedValue.value, versionedValue.version);
+ }).apply(partitionerStr, releaseVersionStr);
+ }
+
+ public static VersionedApplicationState releaseVersion(IInvokableInstance instance)
+ {
+ return unsafeReleaseVersion(instance, instance.config().getString("partitioner"), instance.getReleaseVersionString());
+ }
+
+ public static VersionedApplicationState statusNormal(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens));
+ }
+
+ public static VersionedApplicationState statusWithPortNormal(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS_WITH_PORT, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens));
+ }
+
+ public static VersionedApplicationState statusBootstrapping(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).bootstrapping(tokens));
+ }
+
+ public static VersionedApplicationState statusWithPortBootstrapping(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS_WITH_PORT, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).bootstrapping(tokens));
+ }
+
+ public static VersionedApplicationState statusLeaving(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).leaving(tokens));
+ }
+
+ public static VersionedApplicationState statusWithPortLeaving(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS_WITH_PORT, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).leaving(tokens));
+ }
+
+ public static VersionedValue toVersionedValue(VersionedApplicationState vv)
+ {
+ return VersionedValue.unsafeMakeVersionedValue(vv.value, vv.version);
+ }
+
+ public static ApplicationState toApplicationState(VersionedApplicationState vv)
+ {
+ return ApplicationState.values()[vv.applicationState];
+ }
+
+ public static VersionedApplicationState unsafeVersionedToken(IInvokableInstance instance,
+ ApplicationState applicationState,
+ SerializableBiFunction<IPartitioner, Collection<Token>, VersionedValue> supplier,
+ String partitionerStr, String initialTokenStr)
+ {
+ return instance.appliesOnInstance((String partitionerString, String tokenString) -> {
+ IPartitioner partitioner = FBUtilities.newPartitioner(partitionerString);
+ Token token = partitioner.getTokenFactory().fromString(tokenString);
+
+ VersionedValue versionedValue = supplier.apply(partitioner, Collections.singleton(token));
+ return new VersionedApplicationState(applicationState.ordinal(), versionedValue.value, versionedValue.version);
+ }).apply(partitionerStr, initialTokenStr);
+ }
+
+ public static VersionedApplicationState versionedToken(IInvokableInstance instance, ApplicationState applicationState, SerializableBiFunction<IPartitioner, Collection<Token>, VersionedValue> supplier)
+ {
+ return unsafeVersionedToken(instance, applicationState, supplier, instance.config().getString("partitioner"), instance.config().getString("initial_token"));
+ }
+
+ public void removeFromRing(IInstance peer)
+ {
+ InetAddressAndPort endpoint = toCassandraInetAddressAndPort(peer.broadcastAddress());
+
+ TokenMetadata tokenMetadata = StorageService.instance.getTokenMetadata();
+ tokenMetadata.removeEndpoint(endpoint);
+ Collection<Token> tokens = tokenMetadata.getTokens(endpoint);
+ if (!tokens.isEmpty())
+ tokenMetadata.removeBootstrapTokens(tokens);
+
+ Gossiper.runInGossipStageBlocking(() -> Gossiper.instance.unsafeAnulEndpoint(endpoint));
Review comment:
Is there a reason to not rely on `org.apache.cassandra.service.StorageService#removeNode` or `org.apache.cassandra.service.StorageService#excise(java.util.Collection<org.apache.cassandra.dht.Token>, org.apache.cassandra.locator.InetAddressAndPort)`?
Also, assuming startup has completed, this function would trigger `org.apache.cassandra.service.StorageService#onRemove` which will remove from TokenMetadata and update pending ranges, so I believe we don't need that logic? The only thing it wouldn't do is remove from peers table and wouldn't block on pending ranges.
##########
File path: test/distributed/org/apache/cassandra/distributed/action/GossipHelper.java
##########
@@ -0,0 +1,431 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.distributed.action;
+
+import java.io.IOException;
+import java.io.Serializable;
+import java.net.InetSocketAddress;
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.TimeUnit;
+import java.util.stream.Stream;
+
+import net.openhft.chronicle.core.util.SerializableBiFunction;
+import org.apache.cassandra.db.SystemKeyspace;
+import org.apache.cassandra.dht.IPartitioner;
+import org.apache.cassandra.dht.Token;
+import org.apache.cassandra.distributed.api.IInstance;
+import org.apache.cassandra.distributed.api.IInvokableInstance;
+import org.apache.cassandra.distributed.api.IIsolatedExecutor;
+import org.apache.cassandra.distributed.impl.Instance;
+import org.apache.cassandra.distributed.shared.VersionedApplicationState;
+import org.apache.cassandra.gms.ApplicationState;
+import org.apache.cassandra.gms.EndpointState;
+import org.apache.cassandra.gms.Gossiper;
+import org.apache.cassandra.gms.VersionedValue;
+import org.apache.cassandra.io.util.DataInputBuffer;
+import org.apache.cassandra.io.util.DataOutputBuffer;
+import org.apache.cassandra.locator.InetAddressAndPort;
+import org.apache.cassandra.locator.TokenMetadata;
+import org.apache.cassandra.net.MessagingService;
+import org.apache.cassandra.schema.MigrationManager;
+import org.apache.cassandra.service.PendingRangeCalculatorService;
+import org.apache.cassandra.service.StorageService;
+import org.apache.cassandra.utils.FBUtilities;
+
+import static org.apache.cassandra.distributed.impl.DistributedTestSnitch.toCassandraInetAddressAndPort;
+
+public class GossipHelper
+{
+ public static InstanceAction statusToBootstrap(IInvokableInstance newNode)
+ {
+ return (instance) ->
+ {
+ changeGossipState(instance,
+ newNode,
+ Arrays.asList(tokens(newNode),
+ statusBootstrapping(newNode),
+ statusWithPortBootstrapping(newNode)));
+ };
+ }
+
+ public static InstanceAction statusToNormal(IInvokableInstance peer)
+ {
+ return (target) ->
+ {
+ changeGossipState(target,
+ peer,
+ Arrays.asList(tokens(peer),
+ statusNormal(peer),
+ releaseVersion(peer),
+ statusWithPortNormal(peer)));
+ };
+ }
+
+ /**
+ * This method is unsafe and should be used _only_ when gossip is not used or available: it creates versioned values on the
+ * target instance, which means Gossip versioning gets out of sync. Use a safe couterpart at all times when performing _any_
+ * ring movement operations _or_ if Gossip is used.
+ */
+ public static InstanceAction unsafeStatusToNormal(IInstance peer)
+ {
+ return (target) ->
+ {
+ changeGossipState(target,
+ peer,
+ Arrays.asList(unsafeVersionedToken(target,
+ ApplicationState.TOKENS,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).tokens(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeVersionedToken(target,
+ ApplicationState.STATUS,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeVersionedToken(target,
+ ApplicationState.STATUS_WITH_PORT,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeReleaseVersion(target,
+ peer.config().getString("partitioner"),
+ peer.getReleaseVersionString())));
+ };
+ }
+
+ public static InstanceAction statusToLeaving(IInvokableInstance newNode)
+ {
+ return (instance) -> {
+ changeGossipState(instance,
+ newNode,
+ Arrays.asList(tokens(newNode),
+ statusLeaving(newNode),
+ statusWithPortLeaving(newNode)));
+ };
+ }
+
+ public static InstanceAction bootstrap()
+ {
+ return new BootstrapAction();
+ }
+
+ public static InstanceAction bootstrap(boolean joinRing, Duration waitForBootstrap, Duration waitForSchema)
+ {
+ return new BootstrapAction(joinRing, waitForBootstrap, waitForSchema);
+ }
+
+ public static InstanceAction disseminateGossipState(IInvokableInstance newNode)
+ {
+ return new DisseminateGossipState(newNode);
+ }
+
+ public static InstanceAction pullSchemaFrom(IInvokableInstance pullFrom)
+ {
+ return new PullSchemaFrom(pullFrom);
+ }
+
+ private static InstanceAction disableBinary()
+ {
+ return (instance) -> {
+ instance.runOnInstance(StorageService.instance::stopNativeTransport);
+ };
+ }
+
+ private static class DisseminateGossipState implements InstanceAction
+ {
+ final Map<InetSocketAddress, byte[]> gossipState;
+
+ public DisseminateGossipState(IInvokableInstance... from)
+ {
+ gossipState = new HashMap<>();
+ for (IInvokableInstance node : from)
+ {
+ byte[] epBytes = node.callsOnInstance(() -> {
+ EndpointState epState = Gossiper.instance.getEndpointStateForEndpoint(FBUtilities.getBroadcastAddressAndPort());
+ return toBytes(epState);
+ }).call();
+ gossipState.put(node.broadcastAddress(), epBytes);
+ }
+ }
+
+ public void accept(IInvokableInstance instance)
+ {
+ instance.appliesOnInstance((IIsolatedExecutor.SerializableFunction<Map<InetSocketAddress, byte[]>, Void>)
+ (map) -> {
+ Map<InetAddressAndPort, EndpointState> newState = new HashMap<>();
+ for (Map.Entry<InetSocketAddress, byte[]> e : map.entrySet())
+ newState.put(toCassandraInetAddressAndPort(e.getKey()), fromBytes(e.getValue()));
+
+ Gossiper.runInGossipStageBlocking(() -> {
+ Gossiper.instance.applyStateLocally(newState);
+ });
+ return null;
+ }).apply(gossipState);
+ }
+ }
+
+ public static byte[] toBytes(EndpointState epState)
+ {
+ try (DataOutputBuffer out = new DataOutputBuffer(1024))
+ {
+ EndpointState.serializer.serialize(epState, out, MessagingService.current_version);
+ return out.toByteArray();
+ }
+ catch (IOException e)
+ {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public static EndpointState fromBytes(byte[] bytes)
+ {
+ try (DataInputBuffer in = new DataInputBuffer(bytes))
+ {
+ return EndpointState.serializer.deserialize(in, MessagingService.current_version);
+ }
+ catch (Throwable t)
+ {
+ throw new RuntimeException(t);
+ }
+ }
+
+ private static class PullSchemaFrom implements InstanceAction
+ {
+ final InetSocketAddress pullFrom;
+
+ public PullSchemaFrom(IInvokableInstance pullFrom)
+ {
+ this.pullFrom = pullFrom.broadcastAddress();;
+ }
+
+ public void accept(IInvokableInstance pullTo)
+ {
+ pullTo.acceptsOnInstance((InetSocketAddress pullFrom) -> {
+ InetAddressAndPort endpoint = toCassandraInetAddressAndPort(pullFrom);
+ EndpointState state = Gossiper.instance.getEndpointStateForEndpoint(endpoint);
+ MigrationManager.scheduleSchemaPull(endpoint, state);
+ MigrationManager.waitUntilReadyForBootstrap();
+ }).accept(pullFrom);
+ }
+ }
+
+ private static class BootstrapAction implements InstanceAction, Serializable
+ {
+ private final boolean joinRing;
+ private final Duration waitForBootstrap;
+ private final Duration waitForSchema;
+
+ public BootstrapAction()
+ {
+ this(true, Duration.ofMinutes(10), Duration.ofSeconds(10));
+ }
+
+ public BootstrapAction(boolean joinRing, Duration waitForBootstrap, Duration waitForSchema)
+ {
+ this.joinRing = joinRing;
+ this.waitForBootstrap = waitForBootstrap;
+ this.waitForSchema = waitForSchema;
+ }
+
+ public void accept(IInvokableInstance instance)
+ {
+ instance.appliesOnInstance((String partitionerString, String tokenString) -> {
+ IPartitioner partitioner = FBUtilities.newPartitioner(partitionerString);
+ List<Token> tokens = Collections.singletonList(partitioner.getTokenFactory().fromString(tokenString));
+ try
+ {
+ SystemKeyspace.setBootstrapState(SystemKeyspace.BootstrapState.IN_PROGRESS);
+ StorageService.instance.waitForSchema((int) waitForSchema.toMillis());
+ PendingRangeCalculatorService.instance.blockUntilFinished();
+ StorageService.instance.startBootstrap(tokens).get(waitForBootstrap.toMillis(), TimeUnit.MILLISECONDS);
+ StorageService.instance.setUpDistributedSystemKeyspaces();
+ if (joinRing)
+ StorageService.instance.finishJoiningRing(true, tokens);
+ }
+ catch (Throwable t)
+ {
+ throw new RuntimeException(t);
+ }
+
+ return null;
+ }).apply(instance.config().getString("partitioner"), instance.config().getString("initial_token"));
+ }
+ }
+
+ public static InstanceAction decomission()
+ {
+ return (target) -> {
+ target.runOnInstance(() -> {
+ try
+ {
+ StorageService.instance.decommission(false);
+ }
+ catch (InterruptedException e)
+ {
+ throw new RuntimeException();
+ }
+ });
+ };
+ }
+
+
+ public static VersionedApplicationState tokens(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.TOKENS, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).tokens(tokens));
+ }
+
+ public static VersionedApplicationState unsafeReleaseVersion(IInvokableInstance instance, String partitionerStr, String releaseVersionStr)
+ {
+ return instance.appliesOnInstance((String partitionerString, String releaseVersion) -> {
+ IPartitioner partitioner = FBUtilities.newPartitioner(partitionerString);
+ VersionedValue versionedValue = new VersionedValue.VersionedValueFactory(partitioner).releaseVersion(releaseVersion);
+ return new VersionedApplicationState(ApplicationState.RELEASE_VERSION.ordinal(), versionedValue.value, versionedValue.version);
+ }).apply(partitionerStr, releaseVersionStr);
+ }
+
+ public static VersionedApplicationState releaseVersion(IInvokableInstance instance)
+ {
+ return unsafeReleaseVersion(instance, instance.config().getString("partitioner"), instance.getReleaseVersionString());
+ }
+
+ public static VersionedApplicationState statusNormal(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens));
+ }
+
+ public static VersionedApplicationState statusWithPortNormal(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS_WITH_PORT, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens));
+ }
+
+ public static VersionedApplicationState statusBootstrapping(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).bootstrapping(tokens));
+ }
+
+ public static VersionedApplicationState statusWithPortBootstrapping(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS_WITH_PORT, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).bootstrapping(tokens));
+ }
+
+ public static VersionedApplicationState statusLeaving(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).leaving(tokens));
+ }
+
+ public static VersionedApplicationState statusWithPortLeaving(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS_WITH_PORT, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).leaving(tokens));
+ }
+
+ public static VersionedValue toVersionedValue(VersionedApplicationState vv)
+ {
+ return VersionedValue.unsafeMakeVersionedValue(vv.value, vv.version);
+ }
+
+ public static ApplicationState toApplicationState(VersionedApplicationState vv)
+ {
+ return ApplicationState.values()[vv.applicationState];
+ }
+
+ public static VersionedApplicationState unsafeVersionedToken(IInvokableInstance instance,
+ ApplicationState applicationState,
+ SerializableBiFunction<IPartitioner, Collection<Token>, VersionedValue> supplier,
+ String partitionerStr, String initialTokenStr)
+ {
+ return instance.appliesOnInstance((String partitionerString, String tokenString) -> {
+ IPartitioner partitioner = FBUtilities.newPartitioner(partitionerString);
+ Token token = partitioner.getTokenFactory().fromString(tokenString);
+
+ VersionedValue versionedValue = supplier.apply(partitioner, Collections.singleton(token));
+ return new VersionedApplicationState(applicationState.ordinal(), versionedValue.value, versionedValue.version);
+ }).apply(partitionerStr, initialTokenStr);
+ }
+
+ public static VersionedApplicationState versionedToken(IInvokableInstance instance, ApplicationState applicationState, SerializableBiFunction<IPartitioner, Collection<Token>, VersionedValue> supplier)
+ {
+ return unsafeVersionedToken(instance, applicationState, supplier, instance.config().getString("partitioner"), instance.config().getString("initial_token"));
+ }
+
+ public void removeFromRing(IInstance peer)
+ {
+ InetAddressAndPort endpoint = toCassandraInetAddressAndPort(peer.broadcastAddress());
+
+ TokenMetadata tokenMetadata = StorageService.instance.getTokenMetadata();
+ tokenMetadata.removeEndpoint(endpoint);
+ Collection<Token> tokens = tokenMetadata.getTokens(endpoint);
+ if (!tokens.isEmpty())
+ tokenMetadata.removeBootstrapTokens(tokens);
Review comment:
removeEndpoint already does this, but at the instance level rather than token.
##########
File path: test/distributed/org/apache/cassandra/distributed/action/GossipHelper.java
##########
@@ -0,0 +1,431 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.distributed.action;
+
+import java.io.IOException;
+import java.io.Serializable;
+import java.net.InetSocketAddress;
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.TimeUnit;
+import java.util.stream.Stream;
+
+import net.openhft.chronicle.core.util.SerializableBiFunction;
+import org.apache.cassandra.db.SystemKeyspace;
+import org.apache.cassandra.dht.IPartitioner;
+import org.apache.cassandra.dht.Token;
+import org.apache.cassandra.distributed.api.IInstance;
+import org.apache.cassandra.distributed.api.IInvokableInstance;
+import org.apache.cassandra.distributed.api.IIsolatedExecutor;
+import org.apache.cassandra.distributed.impl.Instance;
+import org.apache.cassandra.distributed.shared.VersionedApplicationState;
+import org.apache.cassandra.gms.ApplicationState;
+import org.apache.cassandra.gms.EndpointState;
+import org.apache.cassandra.gms.Gossiper;
+import org.apache.cassandra.gms.VersionedValue;
+import org.apache.cassandra.io.util.DataInputBuffer;
+import org.apache.cassandra.io.util.DataOutputBuffer;
+import org.apache.cassandra.locator.InetAddressAndPort;
+import org.apache.cassandra.locator.TokenMetadata;
+import org.apache.cassandra.net.MessagingService;
+import org.apache.cassandra.schema.MigrationManager;
+import org.apache.cassandra.service.PendingRangeCalculatorService;
+import org.apache.cassandra.service.StorageService;
+import org.apache.cassandra.utils.FBUtilities;
+
+import static org.apache.cassandra.distributed.impl.DistributedTestSnitch.toCassandraInetAddressAndPort;
+
+public class GossipHelper
+{
+ public static InstanceAction statusToBootstrap(IInvokableInstance newNode)
+ {
+ return (instance) ->
+ {
+ changeGossipState(instance,
+ newNode,
+ Arrays.asList(tokens(newNode),
+ statusBootstrapping(newNode),
+ statusWithPortBootstrapping(newNode)));
+ };
+ }
+
+ public static InstanceAction statusToNormal(IInvokableInstance peer)
+ {
+ return (target) ->
+ {
+ changeGossipState(target,
+ peer,
+ Arrays.asList(tokens(peer),
+ statusNormal(peer),
+ releaseVersion(peer),
+ statusWithPortNormal(peer)));
+ };
+ }
+
+ /**
+ * This method is unsafe and should be used _only_ when gossip is not used or available: it creates versioned values on the
+ * target instance, which means Gossip versioning gets out of sync. Use a safe couterpart at all times when performing _any_
+ * ring movement operations _or_ if Gossip is used.
+ */
+ public static InstanceAction unsafeStatusToNormal(IInstance peer)
+ {
+ return (target) ->
+ {
+ changeGossipState(target,
+ peer,
+ Arrays.asList(unsafeVersionedToken(target,
+ ApplicationState.TOKENS,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).tokens(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeVersionedToken(target,
+ ApplicationState.STATUS,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeVersionedToken(target,
+ ApplicationState.STATUS_WITH_PORT,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeReleaseVersion(target,
+ peer.config().getString("partitioner"),
+ peer.getReleaseVersionString())));
+ };
+ }
+
+ public static InstanceAction statusToLeaving(IInvokableInstance newNode)
+ {
+ return (instance) -> {
+ changeGossipState(instance,
+ newNode,
+ Arrays.asList(tokens(newNode),
+ statusLeaving(newNode),
+ statusWithPortLeaving(newNode)));
+ };
+ }
+
+ public static InstanceAction bootstrap()
+ {
+ return new BootstrapAction();
+ }
+
+ public static InstanceAction bootstrap(boolean joinRing, Duration waitForBootstrap, Duration waitForSchema)
+ {
+ return new BootstrapAction(joinRing, waitForBootstrap, waitForSchema);
+ }
+
+ public static InstanceAction disseminateGossipState(IInvokableInstance newNode)
+ {
+ return new DisseminateGossipState(newNode);
+ }
+
+ public static InstanceAction pullSchemaFrom(IInvokableInstance pullFrom)
+ {
+ return new PullSchemaFrom(pullFrom);
+ }
+
+ private static InstanceAction disableBinary()
+ {
+ return (instance) -> {
+ instance.runOnInstance(StorageService.instance::stopNativeTransport);
+ };
+ }
+
+ private static class DisseminateGossipState implements InstanceAction
+ {
+ final Map<InetSocketAddress, byte[]> gossipState;
+
+ public DisseminateGossipState(IInvokableInstance... from)
+ {
+ gossipState = new HashMap<>();
+ for (IInvokableInstance node : from)
+ {
+ byte[] epBytes = node.callsOnInstance(() -> {
+ EndpointState epState = Gossiper.instance.getEndpointStateForEndpoint(FBUtilities.getBroadcastAddressAndPort());
+ return toBytes(epState);
+ }).call();
+ gossipState.put(node.broadcastAddress(), epBytes);
+ }
+ }
+
+ public void accept(IInvokableInstance instance)
+ {
+ instance.appliesOnInstance((IIsolatedExecutor.SerializableFunction<Map<InetSocketAddress, byte[]>, Void>)
+ (map) -> {
+ Map<InetAddressAndPort, EndpointState> newState = new HashMap<>();
+ for (Map.Entry<InetSocketAddress, byte[]> e : map.entrySet())
+ newState.put(toCassandraInetAddressAndPort(e.getKey()), fromBytes(e.getValue()));
+
+ Gossiper.runInGossipStageBlocking(() -> {
+ Gossiper.instance.applyStateLocally(newState);
+ });
+ return null;
+ }).apply(gossipState);
+ }
+ }
+
+ public static byte[] toBytes(EndpointState epState)
+ {
+ try (DataOutputBuffer out = new DataOutputBuffer(1024))
+ {
+ EndpointState.serializer.serialize(epState, out, MessagingService.current_version);
+ return out.toByteArray();
+ }
+ catch (IOException e)
+ {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public static EndpointState fromBytes(byte[] bytes)
Review comment:
can we make this private?
##########
File path: test/distributed/org/apache/cassandra/distributed/action/GossipHelper.java
##########
@@ -0,0 +1,431 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.distributed.action;
+
+import java.io.IOException;
+import java.io.Serializable;
+import java.net.InetSocketAddress;
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.TimeUnit;
+import java.util.stream.Stream;
+
+import net.openhft.chronicle.core.util.SerializableBiFunction;
+import org.apache.cassandra.db.SystemKeyspace;
+import org.apache.cassandra.dht.IPartitioner;
+import org.apache.cassandra.dht.Token;
+import org.apache.cassandra.distributed.api.IInstance;
+import org.apache.cassandra.distributed.api.IInvokableInstance;
+import org.apache.cassandra.distributed.api.IIsolatedExecutor;
+import org.apache.cassandra.distributed.impl.Instance;
+import org.apache.cassandra.distributed.shared.VersionedApplicationState;
+import org.apache.cassandra.gms.ApplicationState;
+import org.apache.cassandra.gms.EndpointState;
+import org.apache.cassandra.gms.Gossiper;
+import org.apache.cassandra.gms.VersionedValue;
+import org.apache.cassandra.io.util.DataInputBuffer;
+import org.apache.cassandra.io.util.DataOutputBuffer;
+import org.apache.cassandra.locator.InetAddressAndPort;
+import org.apache.cassandra.locator.TokenMetadata;
+import org.apache.cassandra.net.MessagingService;
+import org.apache.cassandra.schema.MigrationManager;
+import org.apache.cassandra.service.PendingRangeCalculatorService;
+import org.apache.cassandra.service.StorageService;
+import org.apache.cassandra.utils.FBUtilities;
+
+import static org.apache.cassandra.distributed.impl.DistributedTestSnitch.toCassandraInetAddressAndPort;
+
+public class GossipHelper
+{
+ public static InstanceAction statusToBootstrap(IInvokableInstance newNode)
+ {
+ return (instance) ->
+ {
+ changeGossipState(instance,
+ newNode,
+ Arrays.asList(tokens(newNode),
+ statusBootstrapping(newNode),
+ statusWithPortBootstrapping(newNode)));
+ };
+ }
+
+ public static InstanceAction statusToNormal(IInvokableInstance peer)
+ {
+ return (target) ->
+ {
+ changeGossipState(target,
+ peer,
+ Arrays.asList(tokens(peer),
+ statusNormal(peer),
+ releaseVersion(peer),
+ statusWithPortNormal(peer)));
+ };
+ }
+
+ /**
+ * This method is unsafe and should be used _only_ when gossip is not used or available: it creates versioned values on the
+ * target instance, which means Gossip versioning gets out of sync. Use a safe couterpart at all times when performing _any_
+ * ring movement operations _or_ if Gossip is used.
+ */
+ public static InstanceAction unsafeStatusToNormal(IInstance peer)
+ {
+ return (target) ->
+ {
+ changeGossipState(target,
+ peer,
+ Arrays.asList(unsafeVersionedToken(target,
+ ApplicationState.TOKENS,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).tokens(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeVersionedToken(target,
+ ApplicationState.STATUS,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeVersionedToken(target,
+ ApplicationState.STATUS_WITH_PORT,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeReleaseVersion(target,
+ peer.config().getString("partitioner"),
+ peer.getReleaseVersionString())));
+ };
+ }
+
+ public static InstanceAction statusToLeaving(IInvokableInstance newNode)
+ {
+ return (instance) -> {
+ changeGossipState(instance,
+ newNode,
+ Arrays.asList(tokens(newNode),
+ statusLeaving(newNode),
+ statusWithPortLeaving(newNode)));
+ };
+ }
+
+ public static InstanceAction bootstrap()
+ {
+ return new BootstrapAction();
+ }
+
+ public static InstanceAction bootstrap(boolean joinRing, Duration waitForBootstrap, Duration waitForSchema)
+ {
+ return new BootstrapAction(joinRing, waitForBootstrap, waitForSchema);
+ }
+
+ public static InstanceAction disseminateGossipState(IInvokableInstance newNode)
+ {
+ return new DisseminateGossipState(newNode);
+ }
+
+ public static InstanceAction pullSchemaFrom(IInvokableInstance pullFrom)
+ {
+ return new PullSchemaFrom(pullFrom);
+ }
+
+ private static InstanceAction disableBinary()
+ {
+ return (instance) -> {
+ instance.runOnInstance(StorageService.instance::stopNativeTransport);
+ };
+ }
+
+ private static class DisseminateGossipState implements InstanceAction
+ {
+ final Map<InetSocketAddress, byte[]> gossipState;
+
+ public DisseminateGossipState(IInvokableInstance... from)
+ {
+ gossipState = new HashMap<>();
+ for (IInvokableInstance node : from)
+ {
+ byte[] epBytes = node.callsOnInstance(() -> {
+ EndpointState epState = Gossiper.instance.getEndpointStateForEndpoint(FBUtilities.getBroadcastAddressAndPort());
+ return toBytes(epState);
+ }).call();
+ gossipState.put(node.broadcastAddress(), epBytes);
+ }
+ }
+
+ public void accept(IInvokableInstance instance)
+ {
+ instance.appliesOnInstance((IIsolatedExecutor.SerializableFunction<Map<InetSocketAddress, byte[]>, Void>)
+ (map) -> {
+ Map<InetAddressAndPort, EndpointState> newState = new HashMap<>();
+ for (Map.Entry<InetSocketAddress, byte[]> e : map.entrySet())
+ newState.put(toCassandraInetAddressAndPort(e.getKey()), fromBytes(e.getValue()));
+
+ Gossiper.runInGossipStageBlocking(() -> {
+ Gossiper.instance.applyStateLocally(newState);
+ });
+ return null;
+ }).apply(gossipState);
+ }
+ }
+
+ public static byte[] toBytes(EndpointState epState)
Review comment:
can we make this private?
##########
File path: test/distributed/org/apache/cassandra/distributed/action/GossipHelper.java
##########
@@ -0,0 +1,431 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.distributed.action;
+
+import java.io.IOException;
+import java.io.Serializable;
+import java.net.InetSocketAddress;
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.TimeUnit;
+import java.util.stream.Stream;
+
+import net.openhft.chronicle.core.util.SerializableBiFunction;
+import org.apache.cassandra.db.SystemKeyspace;
+import org.apache.cassandra.dht.IPartitioner;
+import org.apache.cassandra.dht.Token;
+import org.apache.cassandra.distributed.api.IInstance;
+import org.apache.cassandra.distributed.api.IInvokableInstance;
+import org.apache.cassandra.distributed.api.IIsolatedExecutor;
+import org.apache.cassandra.distributed.impl.Instance;
+import org.apache.cassandra.distributed.shared.VersionedApplicationState;
+import org.apache.cassandra.gms.ApplicationState;
+import org.apache.cassandra.gms.EndpointState;
+import org.apache.cassandra.gms.Gossiper;
+import org.apache.cassandra.gms.VersionedValue;
+import org.apache.cassandra.io.util.DataInputBuffer;
+import org.apache.cassandra.io.util.DataOutputBuffer;
+import org.apache.cassandra.locator.InetAddressAndPort;
+import org.apache.cassandra.locator.TokenMetadata;
+import org.apache.cassandra.net.MessagingService;
+import org.apache.cassandra.schema.MigrationManager;
+import org.apache.cassandra.service.PendingRangeCalculatorService;
+import org.apache.cassandra.service.StorageService;
+import org.apache.cassandra.utils.FBUtilities;
+
+import static org.apache.cassandra.distributed.impl.DistributedTestSnitch.toCassandraInetAddressAndPort;
+
+public class GossipHelper
+{
+ public static InstanceAction statusToBootstrap(IInvokableInstance newNode)
+ {
+ return (instance) ->
+ {
+ changeGossipState(instance,
+ newNode,
+ Arrays.asList(tokens(newNode),
+ statusBootstrapping(newNode),
+ statusWithPortBootstrapping(newNode)));
+ };
+ }
+
+ public static InstanceAction statusToNormal(IInvokableInstance peer)
+ {
+ return (target) ->
+ {
+ changeGossipState(target,
+ peer,
+ Arrays.asList(tokens(peer),
+ statusNormal(peer),
+ releaseVersion(peer),
+ statusWithPortNormal(peer)));
+ };
+ }
+
+ /**
+ * This method is unsafe and should be used _only_ when gossip is not used or available: it creates versioned values on the
+ * target instance, which means Gossip versioning gets out of sync. Use a safe couterpart at all times when performing _any_
+ * ring movement operations _or_ if Gossip is used.
+ */
+ public static InstanceAction unsafeStatusToNormal(IInstance peer)
+ {
+ return (target) ->
+ {
+ changeGossipState(target,
+ peer,
+ Arrays.asList(unsafeVersionedToken(target,
+ ApplicationState.TOKENS,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).tokens(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeVersionedToken(target,
+ ApplicationState.STATUS,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeVersionedToken(target,
+ ApplicationState.STATUS_WITH_PORT,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeReleaseVersion(target,
+ peer.config().getString("partitioner"),
+ peer.getReleaseVersionString())));
+ };
+ }
+
+ public static InstanceAction statusToLeaving(IInvokableInstance newNode)
+ {
+ return (instance) -> {
+ changeGossipState(instance,
+ newNode,
+ Arrays.asList(tokens(newNode),
+ statusLeaving(newNode),
+ statusWithPortLeaving(newNode)));
+ };
+ }
+
+ public static InstanceAction bootstrap()
+ {
+ return new BootstrapAction();
+ }
+
+ public static InstanceAction bootstrap(boolean joinRing, Duration waitForBootstrap, Duration waitForSchema)
+ {
+ return new BootstrapAction(joinRing, waitForBootstrap, waitForSchema);
+ }
+
+ public static InstanceAction disseminateGossipState(IInvokableInstance newNode)
+ {
+ return new DisseminateGossipState(newNode);
+ }
+
+ public static InstanceAction pullSchemaFrom(IInvokableInstance pullFrom)
+ {
+ return new PullSchemaFrom(pullFrom);
+ }
+
+ private static InstanceAction disableBinary()
+ {
+ return (instance) -> {
+ instance.runOnInstance(StorageService.instance::stopNativeTransport);
+ };
+ }
+
+ private static class DisseminateGossipState implements InstanceAction
+ {
+ final Map<InetSocketAddress, byte[]> gossipState;
+
+ public DisseminateGossipState(IInvokableInstance... from)
+ {
+ gossipState = new HashMap<>();
+ for (IInvokableInstance node : from)
+ {
+ byte[] epBytes = node.callsOnInstance(() -> {
+ EndpointState epState = Gossiper.instance.getEndpointStateForEndpoint(FBUtilities.getBroadcastAddressAndPort());
+ return toBytes(epState);
+ }).call();
+ gossipState.put(node.broadcastAddress(), epBytes);
+ }
+ }
+
+ public void accept(IInvokableInstance instance)
+ {
+ instance.appliesOnInstance((IIsolatedExecutor.SerializableFunction<Map<InetSocketAddress, byte[]>, Void>)
+ (map) -> {
+ Map<InetAddressAndPort, EndpointState> newState = new HashMap<>();
+ for (Map.Entry<InetSocketAddress, byte[]> e : map.entrySet())
+ newState.put(toCassandraInetAddressAndPort(e.getKey()), fromBytes(e.getValue()));
+
+ Gossiper.runInGossipStageBlocking(() -> {
+ Gossiper.instance.applyStateLocally(newState);
+ });
+ return null;
+ }).apply(gossipState);
+ }
+ }
+
+ public static byte[] toBytes(EndpointState epState)
+ {
+ try (DataOutputBuffer out = new DataOutputBuffer(1024))
+ {
+ EndpointState.serializer.serialize(epState, out, MessagingService.current_version);
+ return out.toByteArray();
+ }
+ catch (IOException e)
+ {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public static EndpointState fromBytes(byte[] bytes)
+ {
+ try (DataInputBuffer in = new DataInputBuffer(bytes))
+ {
+ return EndpointState.serializer.deserialize(in, MessagingService.current_version);
+ }
+ catch (Throwable t)
+ {
+ throw new RuntimeException(t);
+ }
+ }
+
+ private static class PullSchemaFrom implements InstanceAction
+ {
+ final InetSocketAddress pullFrom;
+
+ public PullSchemaFrom(IInvokableInstance pullFrom)
+ {
+ this.pullFrom = pullFrom.broadcastAddress();;
+ }
+
+ public void accept(IInvokableInstance pullTo)
+ {
+ pullTo.acceptsOnInstance((InetSocketAddress pullFrom) -> {
+ InetAddressAndPort endpoint = toCassandraInetAddressAndPort(pullFrom);
+ EndpointState state = Gossiper.instance.getEndpointStateForEndpoint(endpoint);
+ MigrationManager.scheduleSchemaPull(endpoint, state);
+ MigrationManager.waitUntilReadyForBootstrap();
+ }).accept(pullFrom);
+ }
+ }
+
+ private static class BootstrapAction implements InstanceAction, Serializable
+ {
+ private final boolean joinRing;
+ private final Duration waitForBootstrap;
+ private final Duration waitForSchema;
+
+ public BootstrapAction()
+ {
+ this(true, Duration.ofMinutes(10), Duration.ofSeconds(10));
+ }
+
+ public BootstrapAction(boolean joinRing, Duration waitForBootstrap, Duration waitForSchema)
+ {
+ this.joinRing = joinRing;
+ this.waitForBootstrap = waitForBootstrap;
+ this.waitForSchema = waitForSchema;
+ }
+
+ public void accept(IInvokableInstance instance)
+ {
+ instance.appliesOnInstance((String partitionerString, String tokenString) -> {
+ IPartitioner partitioner = FBUtilities.newPartitioner(partitionerString);
+ List<Token> tokens = Collections.singletonList(partitioner.getTokenFactory().fromString(tokenString));
+ try
+ {
+ SystemKeyspace.setBootstrapState(SystemKeyspace.BootstrapState.IN_PROGRESS);
+ StorageService.instance.waitForSchema((int) waitForSchema.toMillis());
+ PendingRangeCalculatorService.instance.blockUntilFinished();
+ StorageService.instance.startBootstrap(tokens).get(waitForBootstrap.toMillis(), TimeUnit.MILLISECONDS);
+ StorageService.instance.setUpDistributedSystemKeyspaces();
+ if (joinRing)
+ StorageService.instance.finishJoiningRing(true, tokens);
+ }
+ catch (Throwable t)
+ {
+ throw new RuntimeException(t);
+ }
+
+ return null;
+ }).apply(instance.config().getString("partitioner"), instance.config().getString("initial_token"));
+ }
+ }
+
+ public static InstanceAction decomission()
+ {
+ return (target) -> {
+ target.runOnInstance(() -> {
+ try
+ {
+ StorageService.instance.decommission(false);
Review comment:
is there a reason to not use `nodetool decommission`?
`target.nodetool("decommission")`, this would also work on all branches.
##########
File path: test/distributed/org/apache/cassandra/distributed/action/GossipHelper.java
##########
@@ -0,0 +1,431 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.distributed.action;
+
+import java.io.IOException;
+import java.io.Serializable;
+import java.net.InetSocketAddress;
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.TimeUnit;
+import java.util.stream.Stream;
+
+import net.openhft.chronicle.core.util.SerializableBiFunction;
+import org.apache.cassandra.db.SystemKeyspace;
+import org.apache.cassandra.dht.IPartitioner;
+import org.apache.cassandra.dht.Token;
+import org.apache.cassandra.distributed.api.IInstance;
+import org.apache.cassandra.distributed.api.IInvokableInstance;
+import org.apache.cassandra.distributed.api.IIsolatedExecutor;
+import org.apache.cassandra.distributed.impl.Instance;
+import org.apache.cassandra.distributed.shared.VersionedApplicationState;
+import org.apache.cassandra.gms.ApplicationState;
+import org.apache.cassandra.gms.EndpointState;
+import org.apache.cassandra.gms.Gossiper;
+import org.apache.cassandra.gms.VersionedValue;
+import org.apache.cassandra.io.util.DataInputBuffer;
+import org.apache.cassandra.io.util.DataOutputBuffer;
+import org.apache.cassandra.locator.InetAddressAndPort;
+import org.apache.cassandra.locator.TokenMetadata;
+import org.apache.cassandra.net.MessagingService;
+import org.apache.cassandra.schema.MigrationManager;
+import org.apache.cassandra.service.PendingRangeCalculatorService;
+import org.apache.cassandra.service.StorageService;
+import org.apache.cassandra.utils.FBUtilities;
+
+import static org.apache.cassandra.distributed.impl.DistributedTestSnitch.toCassandraInetAddressAndPort;
+
+public class GossipHelper
+{
+ public static InstanceAction statusToBootstrap(IInvokableInstance newNode)
+ {
+ return (instance) ->
+ {
+ changeGossipState(instance,
+ newNode,
+ Arrays.asList(tokens(newNode),
+ statusBootstrapping(newNode),
+ statusWithPortBootstrapping(newNode)));
+ };
+ }
+
+ public static InstanceAction statusToNormal(IInvokableInstance peer)
+ {
+ return (target) ->
+ {
+ changeGossipState(target,
+ peer,
+ Arrays.asList(tokens(peer),
+ statusNormal(peer),
+ releaseVersion(peer),
+ statusWithPortNormal(peer)));
+ };
+ }
+
+ /**
+ * This method is unsafe and should be used _only_ when gossip is not used or available: it creates versioned values on the
+ * target instance, which means Gossip versioning gets out of sync. Use a safe couterpart at all times when performing _any_
+ * ring movement operations _or_ if Gossip is used.
+ */
+ public static InstanceAction unsafeStatusToNormal(IInstance peer)
+ {
+ return (target) ->
+ {
+ changeGossipState(target,
+ peer,
+ Arrays.asList(unsafeVersionedToken(target,
+ ApplicationState.TOKENS,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).tokens(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeVersionedToken(target,
+ ApplicationState.STATUS,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeVersionedToken(target,
+ ApplicationState.STATUS_WITH_PORT,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeReleaseVersion(target,
+ peer.config().getString("partitioner"),
+ peer.getReleaseVersionString())));
+ };
+ }
+
+ public static InstanceAction statusToLeaving(IInvokableInstance newNode)
+ {
+ return (instance) -> {
+ changeGossipState(instance,
+ newNode,
+ Arrays.asList(tokens(newNode),
+ statusLeaving(newNode),
+ statusWithPortLeaving(newNode)));
+ };
+ }
+
+ public static InstanceAction bootstrap()
+ {
+ return new BootstrapAction();
+ }
+
+ public static InstanceAction bootstrap(boolean joinRing, Duration waitForBootstrap, Duration waitForSchema)
+ {
+ return new BootstrapAction(joinRing, waitForBootstrap, waitForSchema);
+ }
+
+ public static InstanceAction disseminateGossipState(IInvokableInstance newNode)
+ {
+ return new DisseminateGossipState(newNode);
+ }
+
+ public static InstanceAction pullSchemaFrom(IInvokableInstance pullFrom)
+ {
+ return new PullSchemaFrom(pullFrom);
+ }
+
+ private static InstanceAction disableBinary()
+ {
+ return (instance) -> {
+ instance.runOnInstance(StorageService.instance::stopNativeTransport);
+ };
+ }
+
+ private static class DisseminateGossipState implements InstanceAction
+ {
+ final Map<InetSocketAddress, byte[]> gossipState;
+
+ public DisseminateGossipState(IInvokableInstance... from)
+ {
+ gossipState = new HashMap<>();
+ for (IInvokableInstance node : from)
+ {
+ byte[] epBytes = node.callsOnInstance(() -> {
+ EndpointState epState = Gossiper.instance.getEndpointStateForEndpoint(FBUtilities.getBroadcastAddressAndPort());
+ return toBytes(epState);
+ }).call();
+ gossipState.put(node.broadcastAddress(), epBytes);
+ }
+ }
+
+ public void accept(IInvokableInstance instance)
+ {
+ instance.appliesOnInstance((IIsolatedExecutor.SerializableFunction<Map<InetSocketAddress, byte[]>, Void>)
+ (map) -> {
+ Map<InetAddressAndPort, EndpointState> newState = new HashMap<>();
+ for (Map.Entry<InetSocketAddress, byte[]> e : map.entrySet())
+ newState.put(toCassandraInetAddressAndPort(e.getKey()), fromBytes(e.getValue()));
+
+ Gossiper.runInGossipStageBlocking(() -> {
+ Gossiper.instance.applyStateLocally(newState);
+ });
+ return null;
+ }).apply(gossipState);
+ }
+ }
+
+ public static byte[] toBytes(EndpointState epState)
+ {
+ try (DataOutputBuffer out = new DataOutputBuffer(1024))
+ {
+ EndpointState.serializer.serialize(epState, out, MessagingService.current_version);
+ return out.toByteArray();
+ }
+ catch (IOException e)
+ {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public static EndpointState fromBytes(byte[] bytes)
+ {
+ try (DataInputBuffer in = new DataInputBuffer(bytes))
+ {
+ return EndpointState.serializer.deserialize(in, MessagingService.current_version);
+ }
+ catch (Throwable t)
+ {
+ throw new RuntimeException(t);
+ }
+ }
+
+ private static class PullSchemaFrom implements InstanceAction
+ {
+ final InetSocketAddress pullFrom;
+
+ public PullSchemaFrom(IInvokableInstance pullFrom)
+ {
+ this.pullFrom = pullFrom.broadcastAddress();;
+ }
+
+ public void accept(IInvokableInstance pullTo)
+ {
+ pullTo.acceptsOnInstance((InetSocketAddress pullFrom) -> {
+ InetAddressAndPort endpoint = toCassandraInetAddressAndPort(pullFrom);
+ EndpointState state = Gossiper.instance.getEndpointStateForEndpoint(endpoint);
+ MigrationManager.scheduleSchemaPull(endpoint, state);
+ MigrationManager.waitUntilReadyForBootstrap();
+ }).accept(pullFrom);
+ }
+ }
+
+ private static class BootstrapAction implements InstanceAction, Serializable
+ {
+ private final boolean joinRing;
+ private final Duration waitForBootstrap;
+ private final Duration waitForSchema;
+
+ public BootstrapAction()
+ {
+ this(true, Duration.ofMinutes(10), Duration.ofSeconds(10));
+ }
+
+ public BootstrapAction(boolean joinRing, Duration waitForBootstrap, Duration waitForSchema)
+ {
+ this.joinRing = joinRing;
+ this.waitForBootstrap = waitForBootstrap;
+ this.waitForSchema = waitForSchema;
+ }
+
+ public void accept(IInvokableInstance instance)
+ {
+ instance.appliesOnInstance((String partitionerString, String tokenString) -> {
+ IPartitioner partitioner = FBUtilities.newPartitioner(partitionerString);
+ List<Token> tokens = Collections.singletonList(partitioner.getTokenFactory().fromString(tokenString));
+ try
+ {
+ SystemKeyspace.setBootstrapState(SystemKeyspace.BootstrapState.IN_PROGRESS);
+ StorageService.instance.waitForSchema((int) waitForSchema.toMillis());
+ PendingRangeCalculatorService.instance.blockUntilFinished();
+ StorageService.instance.startBootstrap(tokens).get(waitForBootstrap.toMillis(), TimeUnit.MILLISECONDS);
+ StorageService.instance.setUpDistributedSystemKeyspaces();
+ if (joinRing)
+ StorageService.instance.finishJoiningRing(true, tokens);
+ }
+ catch (Throwable t)
+ {
+ throw new RuntimeException(t);
+ }
+
+ return null;
+ }).apply(instance.config().getString("partitioner"), instance.config().getString("initial_token"));
+ }
+ }
+
+ public static InstanceAction decomission()
+ {
+ return (target) -> {
+ target.runOnInstance(() -> {
+ try
+ {
+ StorageService.instance.decommission(false);
+ }
+ catch (InterruptedException e)
+ {
+ throw new RuntimeException();
+ }
+ });
+ };
+ }
+
+
+ public static VersionedApplicationState tokens(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.TOKENS, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).tokens(tokens));
+ }
+
+ public static VersionedApplicationState unsafeReleaseVersion(IInvokableInstance instance, String partitionerStr, String releaseVersionStr)
+ {
+ return instance.appliesOnInstance((String partitionerString, String releaseVersion) -> {
+ IPartitioner partitioner = FBUtilities.newPartitioner(partitionerString);
+ VersionedValue versionedValue = new VersionedValue.VersionedValueFactory(partitioner).releaseVersion(releaseVersion);
+ return new VersionedApplicationState(ApplicationState.RELEASE_VERSION.ordinal(), versionedValue.value, versionedValue.version);
+ }).apply(partitionerStr, releaseVersionStr);
+ }
+
+ public static VersionedApplicationState releaseVersion(IInvokableInstance instance)
+ {
+ return unsafeReleaseVersion(instance, instance.config().getString("partitioner"), instance.getReleaseVersionString());
+ }
+
+ public static VersionedApplicationState statusNormal(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens));
+ }
+
+ public static VersionedApplicationState statusWithPortNormal(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS_WITH_PORT, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens));
+ }
+
+ public static VersionedApplicationState statusBootstrapping(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).bootstrapping(tokens));
+ }
+
+ public static VersionedApplicationState statusWithPortBootstrapping(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS_WITH_PORT, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).bootstrapping(tokens));
+ }
+
+ public static VersionedApplicationState statusLeaving(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).leaving(tokens));
+ }
+
+ public static VersionedApplicationState statusWithPortLeaving(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS_WITH_PORT, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).leaving(tokens));
+ }
+
+ public static VersionedValue toVersionedValue(VersionedApplicationState vv)
Review comment:
private?
##########
File path: test/distributed/org/apache/cassandra/distributed/action/GossipHelper.java
##########
@@ -0,0 +1,431 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.distributed.action;
+
+import java.io.IOException;
+import java.io.Serializable;
+import java.net.InetSocketAddress;
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.TimeUnit;
+import java.util.stream.Stream;
+
+import net.openhft.chronicle.core.util.SerializableBiFunction;
+import org.apache.cassandra.db.SystemKeyspace;
+import org.apache.cassandra.dht.IPartitioner;
+import org.apache.cassandra.dht.Token;
+import org.apache.cassandra.distributed.api.IInstance;
+import org.apache.cassandra.distributed.api.IInvokableInstance;
+import org.apache.cassandra.distributed.api.IIsolatedExecutor;
+import org.apache.cassandra.distributed.impl.Instance;
+import org.apache.cassandra.distributed.shared.VersionedApplicationState;
+import org.apache.cassandra.gms.ApplicationState;
+import org.apache.cassandra.gms.EndpointState;
+import org.apache.cassandra.gms.Gossiper;
+import org.apache.cassandra.gms.VersionedValue;
+import org.apache.cassandra.io.util.DataInputBuffer;
+import org.apache.cassandra.io.util.DataOutputBuffer;
+import org.apache.cassandra.locator.InetAddressAndPort;
+import org.apache.cassandra.locator.TokenMetadata;
+import org.apache.cassandra.net.MessagingService;
+import org.apache.cassandra.schema.MigrationManager;
+import org.apache.cassandra.service.PendingRangeCalculatorService;
+import org.apache.cassandra.service.StorageService;
+import org.apache.cassandra.utils.FBUtilities;
+
+import static org.apache.cassandra.distributed.impl.DistributedTestSnitch.toCassandraInetAddressAndPort;
+
+public class GossipHelper
+{
+ public static InstanceAction statusToBootstrap(IInvokableInstance newNode)
+ {
+ return (instance) ->
+ {
+ changeGossipState(instance,
+ newNode,
+ Arrays.asList(tokens(newNode),
+ statusBootstrapping(newNode),
+ statusWithPortBootstrapping(newNode)));
+ };
+ }
+
+ public static InstanceAction statusToNormal(IInvokableInstance peer)
+ {
+ return (target) ->
+ {
+ changeGossipState(target,
+ peer,
+ Arrays.asList(tokens(peer),
+ statusNormal(peer),
+ releaseVersion(peer),
+ statusWithPortNormal(peer)));
+ };
+ }
+
+ /**
+ * This method is unsafe and should be used _only_ when gossip is not used or available: it creates versioned values on the
+ * target instance, which means Gossip versioning gets out of sync. Use a safe couterpart at all times when performing _any_
+ * ring movement operations _or_ if Gossip is used.
+ */
+ public static InstanceAction unsafeStatusToNormal(IInstance peer)
+ {
+ return (target) ->
+ {
+ changeGossipState(target,
+ peer,
+ Arrays.asList(unsafeVersionedToken(target,
+ ApplicationState.TOKENS,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).tokens(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeVersionedToken(target,
+ ApplicationState.STATUS,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeVersionedToken(target,
+ ApplicationState.STATUS_WITH_PORT,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeReleaseVersion(target,
+ peer.config().getString("partitioner"),
+ peer.getReleaseVersionString())));
+ };
+ }
+
+ public static InstanceAction statusToLeaving(IInvokableInstance newNode)
+ {
+ return (instance) -> {
+ changeGossipState(instance,
+ newNode,
+ Arrays.asList(tokens(newNode),
+ statusLeaving(newNode),
+ statusWithPortLeaving(newNode)));
+ };
+ }
+
+ public static InstanceAction bootstrap()
+ {
+ return new BootstrapAction();
+ }
+
+ public static InstanceAction bootstrap(boolean joinRing, Duration waitForBootstrap, Duration waitForSchema)
+ {
+ return new BootstrapAction(joinRing, waitForBootstrap, waitForSchema);
+ }
+
+ public static InstanceAction disseminateGossipState(IInvokableInstance newNode)
+ {
+ return new DisseminateGossipState(newNode);
+ }
+
+ public static InstanceAction pullSchemaFrom(IInvokableInstance pullFrom)
+ {
+ return new PullSchemaFrom(pullFrom);
+ }
+
+ private static InstanceAction disableBinary()
+ {
+ return (instance) -> {
+ instance.runOnInstance(StorageService.instance::stopNativeTransport);
+ };
+ }
+
+ private static class DisseminateGossipState implements InstanceAction
+ {
+ final Map<InetSocketAddress, byte[]> gossipState;
+
+ public DisseminateGossipState(IInvokableInstance... from)
+ {
+ gossipState = new HashMap<>();
+ for (IInvokableInstance node : from)
+ {
+ byte[] epBytes = node.callsOnInstance(() -> {
+ EndpointState epState = Gossiper.instance.getEndpointStateForEndpoint(FBUtilities.getBroadcastAddressAndPort());
+ return toBytes(epState);
+ }).call();
+ gossipState.put(node.broadcastAddress(), epBytes);
+ }
+ }
+
+ public void accept(IInvokableInstance instance)
+ {
+ instance.appliesOnInstance((IIsolatedExecutor.SerializableFunction<Map<InetSocketAddress, byte[]>, Void>)
+ (map) -> {
+ Map<InetAddressAndPort, EndpointState> newState = new HashMap<>();
+ for (Map.Entry<InetSocketAddress, byte[]> e : map.entrySet())
+ newState.put(toCassandraInetAddressAndPort(e.getKey()), fromBytes(e.getValue()));
+
+ Gossiper.runInGossipStageBlocking(() -> {
+ Gossiper.instance.applyStateLocally(newState);
+ });
+ return null;
+ }).apply(gossipState);
+ }
+ }
+
+ public static byte[] toBytes(EndpointState epState)
+ {
+ try (DataOutputBuffer out = new DataOutputBuffer(1024))
+ {
+ EndpointState.serializer.serialize(epState, out, MessagingService.current_version);
+ return out.toByteArray();
+ }
+ catch (IOException e)
+ {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public static EndpointState fromBytes(byte[] bytes)
+ {
+ try (DataInputBuffer in = new DataInputBuffer(bytes))
+ {
+ return EndpointState.serializer.deserialize(in, MessagingService.current_version);
+ }
+ catch (Throwable t)
+ {
+ throw new RuntimeException(t);
+ }
+ }
+
+ private static class PullSchemaFrom implements InstanceAction
+ {
+ final InetSocketAddress pullFrom;
+
+ public PullSchemaFrom(IInvokableInstance pullFrom)
+ {
+ this.pullFrom = pullFrom.broadcastAddress();;
+ }
+
+ public void accept(IInvokableInstance pullTo)
+ {
+ pullTo.acceptsOnInstance((InetSocketAddress pullFrom) -> {
+ InetAddressAndPort endpoint = toCassandraInetAddressAndPort(pullFrom);
+ EndpointState state = Gossiper.instance.getEndpointStateForEndpoint(endpoint);
+ MigrationManager.scheduleSchemaPull(endpoint, state);
+ MigrationManager.waitUntilReadyForBootstrap();
+ }).accept(pullFrom);
+ }
+ }
+
+ private static class BootstrapAction implements InstanceAction, Serializable
+ {
+ private final boolean joinRing;
+ private final Duration waitForBootstrap;
+ private final Duration waitForSchema;
+
+ public BootstrapAction()
+ {
+ this(true, Duration.ofMinutes(10), Duration.ofSeconds(10));
+ }
+
+ public BootstrapAction(boolean joinRing, Duration waitForBootstrap, Duration waitForSchema)
+ {
+ this.joinRing = joinRing;
+ this.waitForBootstrap = waitForBootstrap;
+ this.waitForSchema = waitForSchema;
+ }
+
+ public void accept(IInvokableInstance instance)
+ {
+ instance.appliesOnInstance((String partitionerString, String tokenString) -> {
+ IPartitioner partitioner = FBUtilities.newPartitioner(partitionerString);
+ List<Token> tokens = Collections.singletonList(partitioner.getTokenFactory().fromString(tokenString));
+ try
+ {
+ SystemKeyspace.setBootstrapState(SystemKeyspace.BootstrapState.IN_PROGRESS);
+ StorageService.instance.waitForSchema((int) waitForSchema.toMillis());
+ PendingRangeCalculatorService.instance.blockUntilFinished();
+ StorageService.instance.startBootstrap(tokens).get(waitForBootstrap.toMillis(), TimeUnit.MILLISECONDS);
+ StorageService.instance.setUpDistributedSystemKeyspaces();
+ if (joinRing)
+ StorageService.instance.finishJoiningRing(true, tokens);
+ }
+ catch (Throwable t)
+ {
+ throw new RuntimeException(t);
+ }
+
+ return null;
+ }).apply(instance.config().getString("partitioner"), instance.config().getString("initial_token"));
+ }
+ }
+
+ public static InstanceAction decomission()
+ {
+ return (target) -> {
+ target.runOnInstance(() -> {
+ try
+ {
+ StorageService.instance.decommission(false);
+ }
+ catch (InterruptedException e)
+ {
+ throw new RuntimeException();
+ }
+ });
+ };
+ }
+
+
+ public static VersionedApplicationState tokens(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.TOKENS, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).tokens(tokens));
+ }
+
+ public static VersionedApplicationState unsafeReleaseVersion(IInvokableInstance instance, String partitionerStr, String releaseVersionStr)
+ {
+ return instance.appliesOnInstance((String partitionerString, String releaseVersion) -> {
+ IPartitioner partitioner = FBUtilities.newPartitioner(partitionerString);
+ VersionedValue versionedValue = new VersionedValue.VersionedValueFactory(partitioner).releaseVersion(releaseVersion);
+ return new VersionedApplicationState(ApplicationState.RELEASE_VERSION.ordinal(), versionedValue.value, versionedValue.version);
+ }).apply(partitionerStr, releaseVersionStr);
+ }
+
+ public static VersionedApplicationState releaseVersion(IInvokableInstance instance)
+ {
+ return unsafeReleaseVersion(instance, instance.config().getString("partitioner"), instance.getReleaseVersionString());
+ }
+
+ public static VersionedApplicationState statusNormal(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens));
+ }
+
+ public static VersionedApplicationState statusWithPortNormal(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS_WITH_PORT, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens));
+ }
+
+ public static VersionedApplicationState statusBootstrapping(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).bootstrapping(tokens));
+ }
+
+ public static VersionedApplicationState statusWithPortBootstrapping(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS_WITH_PORT, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).bootstrapping(tokens));
+ }
+
+ public static VersionedApplicationState statusLeaving(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).leaving(tokens));
+ }
+
+ public static VersionedApplicationState statusWithPortLeaving(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS_WITH_PORT, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).leaving(tokens));
+ }
+
+ public static VersionedValue toVersionedValue(VersionedApplicationState vv)
+ {
+ return VersionedValue.unsafeMakeVersionedValue(vv.value, vv.version);
+ }
+
+ public static ApplicationState toApplicationState(VersionedApplicationState vv)
+ {
+ return ApplicationState.values()[vv.applicationState];
+ }
+
+ public static VersionedApplicationState unsafeVersionedToken(IInvokableInstance instance,
+ ApplicationState applicationState,
+ SerializableBiFunction<IPartitioner, Collection<Token>, VersionedValue> supplier,
+ String partitionerStr, String initialTokenStr)
+ {
+ return instance.appliesOnInstance((String partitionerString, String tokenString) -> {
+ IPartitioner partitioner = FBUtilities.newPartitioner(partitionerString);
+ Token token = partitioner.getTokenFactory().fromString(tokenString);
+
+ VersionedValue versionedValue = supplier.apply(partitioner, Collections.singleton(token));
+ return new VersionedApplicationState(applicationState.ordinal(), versionedValue.value, versionedValue.version);
+ }).apply(partitionerStr, initialTokenStr);
+ }
+
+ public static VersionedApplicationState versionedToken(IInvokableInstance instance, ApplicationState applicationState, SerializableBiFunction<IPartitioner, Collection<Token>, VersionedValue> supplier)
+ {
+ return unsafeVersionedToken(instance, applicationState, supplier, instance.config().getString("partitioner"), instance.config().getString("initial_token"));
+ }
+
+ public void removeFromRing(IInstance peer)
Review comment:
calling this function seems to always throw an assert error, I also see its dead code; should we remove?
##########
File path: test/distributed/org/apache/cassandra/distributed/action/GossipHelper.java
##########
@@ -0,0 +1,431 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.distributed.action;
+
+import java.io.IOException;
+import java.io.Serializable;
+import java.net.InetSocketAddress;
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.TimeUnit;
+import java.util.stream.Stream;
+
+import net.openhft.chronicle.core.util.SerializableBiFunction;
+import org.apache.cassandra.db.SystemKeyspace;
+import org.apache.cassandra.dht.IPartitioner;
+import org.apache.cassandra.dht.Token;
+import org.apache.cassandra.distributed.api.IInstance;
+import org.apache.cassandra.distributed.api.IInvokableInstance;
+import org.apache.cassandra.distributed.api.IIsolatedExecutor;
+import org.apache.cassandra.distributed.impl.Instance;
+import org.apache.cassandra.distributed.shared.VersionedApplicationState;
+import org.apache.cassandra.gms.ApplicationState;
+import org.apache.cassandra.gms.EndpointState;
+import org.apache.cassandra.gms.Gossiper;
+import org.apache.cassandra.gms.VersionedValue;
+import org.apache.cassandra.io.util.DataInputBuffer;
+import org.apache.cassandra.io.util.DataOutputBuffer;
+import org.apache.cassandra.locator.InetAddressAndPort;
+import org.apache.cassandra.locator.TokenMetadata;
+import org.apache.cassandra.net.MessagingService;
+import org.apache.cassandra.schema.MigrationManager;
+import org.apache.cassandra.service.PendingRangeCalculatorService;
+import org.apache.cassandra.service.StorageService;
+import org.apache.cassandra.utils.FBUtilities;
+
+import static org.apache.cassandra.distributed.impl.DistributedTestSnitch.toCassandraInetAddressAndPort;
+
+public class GossipHelper
+{
+ public static InstanceAction statusToBootstrap(IInvokableInstance newNode)
+ {
+ return (instance) ->
+ {
+ changeGossipState(instance,
+ newNode,
+ Arrays.asList(tokens(newNode),
+ statusBootstrapping(newNode),
+ statusWithPortBootstrapping(newNode)));
+ };
+ }
+
+ public static InstanceAction statusToNormal(IInvokableInstance peer)
+ {
+ return (target) ->
+ {
+ changeGossipState(target,
+ peer,
+ Arrays.asList(tokens(peer),
+ statusNormal(peer),
+ releaseVersion(peer),
+ statusWithPortNormal(peer)));
+ };
+ }
+
+ /**
+ * This method is unsafe and should be used _only_ when gossip is not used or available: it creates versioned values on the
+ * target instance, which means Gossip versioning gets out of sync. Use a safe couterpart at all times when performing _any_
+ * ring movement operations _or_ if Gossip is used.
+ */
+ public static InstanceAction unsafeStatusToNormal(IInstance peer)
+ {
+ return (target) ->
+ {
+ changeGossipState(target,
+ peer,
+ Arrays.asList(unsafeVersionedToken(target,
+ ApplicationState.TOKENS,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).tokens(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeVersionedToken(target,
+ ApplicationState.STATUS,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeVersionedToken(target,
+ ApplicationState.STATUS_WITH_PORT,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeReleaseVersion(target,
+ peer.config().getString("partitioner"),
+ peer.getReleaseVersionString())));
+ };
+ }
+
+ public static InstanceAction statusToLeaving(IInvokableInstance newNode)
+ {
+ return (instance) -> {
+ changeGossipState(instance,
+ newNode,
+ Arrays.asList(tokens(newNode),
+ statusLeaving(newNode),
+ statusWithPortLeaving(newNode)));
+ };
+ }
+
+ public static InstanceAction bootstrap()
+ {
+ return new BootstrapAction();
+ }
+
+ public static InstanceAction bootstrap(boolean joinRing, Duration waitForBootstrap, Duration waitForSchema)
+ {
+ return new BootstrapAction(joinRing, waitForBootstrap, waitForSchema);
+ }
+
+ public static InstanceAction disseminateGossipState(IInvokableInstance newNode)
+ {
+ return new DisseminateGossipState(newNode);
+ }
+
+ public static InstanceAction pullSchemaFrom(IInvokableInstance pullFrom)
+ {
+ return new PullSchemaFrom(pullFrom);
+ }
+
+ private static InstanceAction disableBinary()
+ {
+ return (instance) -> {
+ instance.runOnInstance(StorageService.instance::stopNativeTransport);
+ };
+ }
+
+ private static class DisseminateGossipState implements InstanceAction
+ {
+ final Map<InetSocketAddress, byte[]> gossipState;
+
+ public DisseminateGossipState(IInvokableInstance... from)
+ {
+ gossipState = new HashMap<>();
+ for (IInvokableInstance node : from)
+ {
+ byte[] epBytes = node.callsOnInstance(() -> {
+ EndpointState epState = Gossiper.instance.getEndpointStateForEndpoint(FBUtilities.getBroadcastAddressAndPort());
+ return toBytes(epState);
+ }).call();
+ gossipState.put(node.broadcastAddress(), epBytes);
+ }
+ }
+
+ public void accept(IInvokableInstance instance)
+ {
+ instance.appliesOnInstance((IIsolatedExecutor.SerializableFunction<Map<InetSocketAddress, byte[]>, Void>)
+ (map) -> {
+ Map<InetAddressAndPort, EndpointState> newState = new HashMap<>();
+ for (Map.Entry<InetSocketAddress, byte[]> e : map.entrySet())
+ newState.put(toCassandraInetAddressAndPort(e.getKey()), fromBytes(e.getValue()));
+
+ Gossiper.runInGossipStageBlocking(() -> {
+ Gossiper.instance.applyStateLocally(newState);
+ });
+ return null;
+ }).apply(gossipState);
+ }
+ }
+
+ public static byte[] toBytes(EndpointState epState)
+ {
+ try (DataOutputBuffer out = new DataOutputBuffer(1024))
+ {
+ EndpointState.serializer.serialize(epState, out, MessagingService.current_version);
+ return out.toByteArray();
+ }
+ catch (IOException e)
+ {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public static EndpointState fromBytes(byte[] bytes)
+ {
+ try (DataInputBuffer in = new DataInputBuffer(bytes))
+ {
+ return EndpointState.serializer.deserialize(in, MessagingService.current_version);
+ }
+ catch (Throwable t)
+ {
+ throw new RuntimeException(t);
+ }
+ }
+
+ private static class PullSchemaFrom implements InstanceAction
+ {
+ final InetSocketAddress pullFrom;
+
+ public PullSchemaFrom(IInvokableInstance pullFrom)
+ {
+ this.pullFrom = pullFrom.broadcastAddress();;
+ }
+
+ public void accept(IInvokableInstance pullTo)
+ {
+ pullTo.acceptsOnInstance((InetSocketAddress pullFrom) -> {
+ InetAddressAndPort endpoint = toCassandraInetAddressAndPort(pullFrom);
+ EndpointState state = Gossiper.instance.getEndpointStateForEndpoint(endpoint);
+ MigrationManager.scheduleSchemaPull(endpoint, state);
+ MigrationManager.waitUntilReadyForBootstrap();
+ }).accept(pullFrom);
+ }
+ }
+
+ private static class BootstrapAction implements InstanceAction, Serializable
+ {
+ private final boolean joinRing;
+ private final Duration waitForBootstrap;
+ private final Duration waitForSchema;
+
+ public BootstrapAction()
+ {
+ this(true, Duration.ofMinutes(10), Duration.ofSeconds(10));
+ }
+
+ public BootstrapAction(boolean joinRing, Duration waitForBootstrap, Duration waitForSchema)
+ {
+ this.joinRing = joinRing;
+ this.waitForBootstrap = waitForBootstrap;
+ this.waitForSchema = waitForSchema;
+ }
+
+ public void accept(IInvokableInstance instance)
+ {
+ instance.appliesOnInstance((String partitionerString, String tokenString) -> {
+ IPartitioner partitioner = FBUtilities.newPartitioner(partitionerString);
+ List<Token> tokens = Collections.singletonList(partitioner.getTokenFactory().fromString(tokenString));
+ try
+ {
+ SystemKeyspace.setBootstrapState(SystemKeyspace.BootstrapState.IN_PROGRESS);
+ StorageService.instance.waitForSchema((int) waitForSchema.toMillis());
+ PendingRangeCalculatorService.instance.blockUntilFinished();
+ StorageService.instance.startBootstrap(tokens).get(waitForBootstrap.toMillis(), TimeUnit.MILLISECONDS);
+ StorageService.instance.setUpDistributedSystemKeyspaces();
+ if (joinRing)
+ StorageService.instance.finishJoiningRing(true, tokens);
+ }
+ catch (Throwable t)
+ {
+ throw new RuntimeException(t);
+ }
+
+ return null;
+ }).apply(instance.config().getString("partitioner"), instance.config().getString("initial_token"));
+ }
+ }
+
+ public static InstanceAction decomission()
+ {
+ return (target) -> {
+ target.runOnInstance(() -> {
+ try
+ {
+ StorageService.instance.decommission(false);
+ }
+ catch (InterruptedException e)
+ {
+ throw new RuntimeException();
+ }
+ });
+ };
+ }
+
+
+ public static VersionedApplicationState tokens(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.TOKENS, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).tokens(tokens));
+ }
+
+ public static VersionedApplicationState unsafeReleaseVersion(IInvokableInstance instance, String partitionerStr, String releaseVersionStr)
+ {
+ return instance.appliesOnInstance((String partitionerString, String releaseVersion) -> {
+ IPartitioner partitioner = FBUtilities.newPartitioner(partitionerString);
+ VersionedValue versionedValue = new VersionedValue.VersionedValueFactory(partitioner).releaseVersion(releaseVersion);
+ return new VersionedApplicationState(ApplicationState.RELEASE_VERSION.ordinal(), versionedValue.value, versionedValue.version);
+ }).apply(partitionerStr, releaseVersionStr);
+ }
+
+ public static VersionedApplicationState releaseVersion(IInvokableInstance instance)
+ {
+ return unsafeReleaseVersion(instance, instance.config().getString("partitioner"), instance.getReleaseVersionString());
+ }
+
+ public static VersionedApplicationState statusNormal(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens));
+ }
+
+ public static VersionedApplicationState statusWithPortNormal(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS_WITH_PORT, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens));
+ }
+
+ public static VersionedApplicationState statusBootstrapping(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).bootstrapping(tokens));
+ }
+
+ public static VersionedApplicationState statusWithPortBootstrapping(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS_WITH_PORT, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).bootstrapping(tokens));
+ }
+
+ public static VersionedApplicationState statusLeaving(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).leaving(tokens));
+ }
+
+ public static VersionedApplicationState statusWithPortLeaving(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS_WITH_PORT, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).leaving(tokens));
+ }
+
+ public static VersionedValue toVersionedValue(VersionedApplicationState vv)
+ {
+ return VersionedValue.unsafeMakeVersionedValue(vv.value, vv.version);
+ }
+
+ public static ApplicationState toApplicationState(VersionedApplicationState vv)
+ {
+ return ApplicationState.values()[vv.applicationState];
+ }
+
+ public static VersionedApplicationState unsafeVersionedToken(IInvokableInstance instance,
+ ApplicationState applicationState,
+ SerializableBiFunction<IPartitioner, Collection<Token>, VersionedValue> supplier,
+ String partitionerStr, String initialTokenStr)
+ {
+ return instance.appliesOnInstance((String partitionerString, String tokenString) -> {
+ IPartitioner partitioner = FBUtilities.newPartitioner(partitionerString);
+ Token token = partitioner.getTokenFactory().fromString(tokenString);
+
+ VersionedValue versionedValue = supplier.apply(partitioner, Collections.singleton(token));
+ return new VersionedApplicationState(applicationState.ordinal(), versionedValue.value, versionedValue.version);
+ }).apply(partitionerStr, initialTokenStr);
+ }
+
+ public static VersionedApplicationState versionedToken(IInvokableInstance instance, ApplicationState applicationState, SerializableBiFunction<IPartitioner, Collection<Token>, VersionedValue> supplier)
+ {
+ return unsafeVersionedToken(instance, applicationState, supplier, instance.config().getString("partitioner"), instance.config().getString("initial_token"));
+ }
+
+ public void removeFromRing(IInstance peer)
+ {
+ InetAddressAndPort endpoint = toCassandraInetAddressAndPort(peer.broadcastAddress());
+
+ TokenMetadata tokenMetadata = StorageService.instance.getTokenMetadata();
+ tokenMetadata.removeEndpoint(endpoint);
+ Collection<Token> tokens = tokenMetadata.getTokens(endpoint);
Review comment:
This should always throw a assert error as the endpoint is no longer in the TokenMetadata.
##########
File path: test/distributed/org/apache/cassandra/distributed/action/GossipHelper.java
##########
@@ -0,0 +1,431 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.distributed.action;
+
+import java.io.IOException;
+import java.io.Serializable;
+import java.net.InetSocketAddress;
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.TimeUnit;
+import java.util.stream.Stream;
+
+import net.openhft.chronicle.core.util.SerializableBiFunction;
+import org.apache.cassandra.db.SystemKeyspace;
+import org.apache.cassandra.dht.IPartitioner;
+import org.apache.cassandra.dht.Token;
+import org.apache.cassandra.distributed.api.IInstance;
+import org.apache.cassandra.distributed.api.IInvokableInstance;
+import org.apache.cassandra.distributed.api.IIsolatedExecutor;
+import org.apache.cassandra.distributed.impl.Instance;
+import org.apache.cassandra.distributed.shared.VersionedApplicationState;
+import org.apache.cassandra.gms.ApplicationState;
+import org.apache.cassandra.gms.EndpointState;
+import org.apache.cassandra.gms.Gossiper;
+import org.apache.cassandra.gms.VersionedValue;
+import org.apache.cassandra.io.util.DataInputBuffer;
+import org.apache.cassandra.io.util.DataOutputBuffer;
+import org.apache.cassandra.locator.InetAddressAndPort;
+import org.apache.cassandra.locator.TokenMetadata;
+import org.apache.cassandra.net.MessagingService;
+import org.apache.cassandra.schema.MigrationManager;
+import org.apache.cassandra.service.PendingRangeCalculatorService;
+import org.apache.cassandra.service.StorageService;
+import org.apache.cassandra.utils.FBUtilities;
+
+import static org.apache.cassandra.distributed.impl.DistributedTestSnitch.toCassandraInetAddressAndPort;
+
+public class GossipHelper
+{
+ public static InstanceAction statusToBootstrap(IInvokableInstance newNode)
+ {
+ return (instance) ->
+ {
+ changeGossipState(instance,
+ newNode,
+ Arrays.asList(tokens(newNode),
+ statusBootstrapping(newNode),
+ statusWithPortBootstrapping(newNode)));
+ };
+ }
+
+ public static InstanceAction statusToNormal(IInvokableInstance peer)
+ {
+ return (target) ->
+ {
+ changeGossipState(target,
+ peer,
+ Arrays.asList(tokens(peer),
+ statusNormal(peer),
+ releaseVersion(peer),
+ statusWithPortNormal(peer)));
+ };
+ }
+
+ /**
+ * This method is unsafe and should be used _only_ when gossip is not used or available: it creates versioned values on the
+ * target instance, which means Gossip versioning gets out of sync. Use a safe couterpart at all times when performing _any_
+ * ring movement operations _or_ if Gossip is used.
+ */
+ public static InstanceAction unsafeStatusToNormal(IInstance peer)
+ {
+ return (target) ->
+ {
+ changeGossipState(target,
+ peer,
+ Arrays.asList(unsafeVersionedToken(target,
+ ApplicationState.TOKENS,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).tokens(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeVersionedToken(target,
+ ApplicationState.STATUS,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeVersionedToken(target,
+ ApplicationState.STATUS_WITH_PORT,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeReleaseVersion(target,
+ peer.config().getString("partitioner"),
+ peer.getReleaseVersionString())));
+ };
+ }
+
+ public static InstanceAction statusToLeaving(IInvokableInstance newNode)
+ {
+ return (instance) -> {
+ changeGossipState(instance,
+ newNode,
+ Arrays.asList(tokens(newNode),
+ statusLeaving(newNode),
+ statusWithPortLeaving(newNode)));
+ };
+ }
+
+ public static InstanceAction bootstrap()
+ {
+ return new BootstrapAction();
+ }
+
+ public static InstanceAction bootstrap(boolean joinRing, Duration waitForBootstrap, Duration waitForSchema)
+ {
+ return new BootstrapAction(joinRing, waitForBootstrap, waitForSchema);
+ }
+
+ public static InstanceAction disseminateGossipState(IInvokableInstance newNode)
+ {
+ return new DisseminateGossipState(newNode);
+ }
+
+ public static InstanceAction pullSchemaFrom(IInvokableInstance pullFrom)
+ {
+ return new PullSchemaFrom(pullFrom);
+ }
+
+ private static InstanceAction disableBinary()
+ {
+ return (instance) -> {
+ instance.runOnInstance(StorageService.instance::stopNativeTransport);
+ };
+ }
+
+ private static class DisseminateGossipState implements InstanceAction
+ {
+ final Map<InetSocketAddress, byte[]> gossipState;
+
+ public DisseminateGossipState(IInvokableInstance... from)
+ {
+ gossipState = new HashMap<>();
+ for (IInvokableInstance node : from)
+ {
+ byte[] epBytes = node.callsOnInstance(() -> {
+ EndpointState epState = Gossiper.instance.getEndpointStateForEndpoint(FBUtilities.getBroadcastAddressAndPort());
+ return toBytes(epState);
+ }).call();
+ gossipState.put(node.broadcastAddress(), epBytes);
+ }
+ }
+
+ public void accept(IInvokableInstance instance)
+ {
+ instance.appliesOnInstance((IIsolatedExecutor.SerializableFunction<Map<InetSocketAddress, byte[]>, Void>)
+ (map) -> {
+ Map<InetAddressAndPort, EndpointState> newState = new HashMap<>();
+ for (Map.Entry<InetSocketAddress, byte[]> e : map.entrySet())
+ newState.put(toCassandraInetAddressAndPort(e.getKey()), fromBytes(e.getValue()));
+
+ Gossiper.runInGossipStageBlocking(() -> {
+ Gossiper.instance.applyStateLocally(newState);
+ });
+ return null;
+ }).apply(gossipState);
+ }
+ }
+
+ public static byte[] toBytes(EndpointState epState)
+ {
+ try (DataOutputBuffer out = new DataOutputBuffer(1024))
+ {
+ EndpointState.serializer.serialize(epState, out, MessagingService.current_version);
+ return out.toByteArray();
+ }
+ catch (IOException e)
+ {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public static EndpointState fromBytes(byte[] bytes)
+ {
+ try (DataInputBuffer in = new DataInputBuffer(bytes))
+ {
+ return EndpointState.serializer.deserialize(in, MessagingService.current_version);
+ }
+ catch (Throwable t)
+ {
+ throw new RuntimeException(t);
+ }
+ }
+
+ private static class PullSchemaFrom implements InstanceAction
+ {
+ final InetSocketAddress pullFrom;
+
+ public PullSchemaFrom(IInvokableInstance pullFrom)
+ {
+ this.pullFrom = pullFrom.broadcastAddress();;
+ }
+
+ public void accept(IInvokableInstance pullTo)
+ {
+ pullTo.acceptsOnInstance((InetSocketAddress pullFrom) -> {
+ InetAddressAndPort endpoint = toCassandraInetAddressAndPort(pullFrom);
+ EndpointState state = Gossiper.instance.getEndpointStateForEndpoint(endpoint);
+ MigrationManager.scheduleSchemaPull(endpoint, state);
+ MigrationManager.waitUntilReadyForBootstrap();
+ }).accept(pullFrom);
+ }
+ }
+
+ private static class BootstrapAction implements InstanceAction, Serializable
+ {
+ private final boolean joinRing;
+ private final Duration waitForBootstrap;
+ private final Duration waitForSchema;
+
+ public BootstrapAction()
+ {
+ this(true, Duration.ofMinutes(10), Duration.ofSeconds(10));
+ }
+
+ public BootstrapAction(boolean joinRing, Duration waitForBootstrap, Duration waitForSchema)
+ {
+ this.joinRing = joinRing;
+ this.waitForBootstrap = waitForBootstrap;
+ this.waitForSchema = waitForSchema;
+ }
+
+ public void accept(IInvokableInstance instance)
+ {
+ instance.appliesOnInstance((String partitionerString, String tokenString) -> {
+ IPartitioner partitioner = FBUtilities.newPartitioner(partitionerString);
+ List<Token> tokens = Collections.singletonList(partitioner.getTokenFactory().fromString(tokenString));
+ try
+ {
+ SystemKeyspace.setBootstrapState(SystemKeyspace.BootstrapState.IN_PROGRESS);
+ StorageService.instance.waitForSchema((int) waitForSchema.toMillis());
+ PendingRangeCalculatorService.instance.blockUntilFinished();
+ StorageService.instance.startBootstrap(tokens).get(waitForBootstrap.toMillis(), TimeUnit.MILLISECONDS);
+ StorageService.instance.setUpDistributedSystemKeyspaces();
+ if (joinRing)
+ StorageService.instance.finishJoiningRing(true, tokens);
+ }
+ catch (Throwable t)
+ {
+ throw new RuntimeException(t);
+ }
+
+ return null;
+ }).apply(instance.config().getString("partitioner"), instance.config().getString("initial_token"));
+ }
+ }
+
+ public static InstanceAction decomission()
+ {
+ return (target) -> {
+ target.runOnInstance(() -> {
+ try
+ {
+ StorageService.instance.decommission(false);
+ }
+ catch (InterruptedException e)
+ {
+ throw new RuntimeException();
+ }
+ });
+ };
+ }
+
+
+ public static VersionedApplicationState tokens(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.TOKENS, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).tokens(tokens));
+ }
+
+ public static VersionedApplicationState unsafeReleaseVersion(IInvokableInstance instance, String partitionerStr, String releaseVersionStr)
+ {
+ return instance.appliesOnInstance((String partitionerString, String releaseVersion) -> {
+ IPartitioner partitioner = FBUtilities.newPartitioner(partitionerString);
+ VersionedValue versionedValue = new VersionedValue.VersionedValueFactory(partitioner).releaseVersion(releaseVersion);
+ return new VersionedApplicationState(ApplicationState.RELEASE_VERSION.ordinal(), versionedValue.value, versionedValue.version);
+ }).apply(partitionerStr, releaseVersionStr);
+ }
+
+ public static VersionedApplicationState releaseVersion(IInvokableInstance instance)
+ {
+ return unsafeReleaseVersion(instance, instance.config().getString("partitioner"), instance.getReleaseVersionString());
+ }
+
+ public static VersionedApplicationState statusNormal(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens));
+ }
+
+ public static VersionedApplicationState statusWithPortNormal(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS_WITH_PORT, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens));
+ }
+
+ public static VersionedApplicationState statusBootstrapping(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).bootstrapping(tokens));
+ }
+
+ public static VersionedApplicationState statusWithPortBootstrapping(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS_WITH_PORT, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).bootstrapping(tokens));
+ }
+
+ public static VersionedApplicationState statusLeaving(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).leaving(tokens));
+ }
+
+ public static VersionedApplicationState statusWithPortLeaving(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS_WITH_PORT, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).leaving(tokens));
+ }
+
+ public static VersionedValue toVersionedValue(VersionedApplicationState vv)
+ {
+ return VersionedValue.unsafeMakeVersionedValue(vv.value, vv.version);
+ }
+
+ public static ApplicationState toApplicationState(VersionedApplicationState vv)
+ {
+ return ApplicationState.values()[vv.applicationState];
+ }
+
+ public static VersionedApplicationState unsafeVersionedToken(IInvokableInstance instance,
+ ApplicationState applicationState,
+ SerializableBiFunction<IPartitioner, Collection<Token>, VersionedValue> supplier,
+ String partitionerStr, String initialTokenStr)
+ {
+ return instance.appliesOnInstance((String partitionerString, String tokenString) -> {
+ IPartitioner partitioner = FBUtilities.newPartitioner(partitionerString);
+ Token token = partitioner.getTokenFactory().fromString(tokenString);
+
+ VersionedValue versionedValue = supplier.apply(partitioner, Collections.singleton(token));
+ return new VersionedApplicationState(applicationState.ordinal(), versionedValue.value, versionedValue.version);
+ }).apply(partitionerStr, initialTokenStr);
+ }
+
+ public static VersionedApplicationState versionedToken(IInvokableInstance instance, ApplicationState applicationState, SerializableBiFunction<IPartitioner, Collection<Token>, VersionedValue> supplier)
+ {
+ return unsafeVersionedToken(instance, applicationState, supplier, instance.config().getString("partitioner"), instance.config().getString("initial_token"));
+ }
+
+ public void removeFromRing(IInstance peer)
+ {
+ InetAddressAndPort endpoint = toCassandraInetAddressAndPort(peer.broadcastAddress());
+
+ TokenMetadata tokenMetadata = StorageService.instance.getTokenMetadata();
+ tokenMetadata.removeEndpoint(endpoint);
+ Collection<Token> tokens = tokenMetadata.getTokens(endpoint);
+ if (!tokens.isEmpty())
+ tokenMetadata.removeBootstrapTokens(tokens);
+
+ Gossiper.runInGossipStageBlocking(() -> Gossiper.instance.unsafeAnulEndpoint(endpoint));
+
+ SystemKeyspace.removeEndpoint(endpoint);
+ PendingRangeCalculatorService.instance.update();
+ PendingRangeCalculatorService.instance.blockUntilFinished();
+ }
+
+ public static void changeGossipState(Stream<IInvokableInstance> targets, Instance peer, List<VersionedApplicationState> newState)
+ {
+ targets.forEach((instance) -> {
+ changeGossipState(instance, peer, newState);
+ });
+ }
+
+ /**
+ * Changes gossip state of the `peer` on `target`
+ */
+ public static void changeGossipState(IInvokableInstance target, IInstance peer, List<VersionedApplicationState> newState)
+ {
+ int version = peer.isShutdown() ? MessagingService.current_version : peer.getMessagingVersion();
+
+ target.appliesOnInstance((InetSocketAddress addr, UUID hostId, Integer messagingVersion) -> {
+ InetAddressAndPort endpoint = toCassandraInetAddressAndPort(addr);
+ StorageService storageService = StorageService.instance;
+
+ Gossiper.runInGossipStageBlocking(() -> {
+ EndpointState state = Gossiper.instance.getEndpointStateForEndpoint(endpoint);
+ if (state == null)
+ {
+ Gossiper.instance.initializeNodeUnsafe(endpoint, hostId, 1);
+ state = Gossiper.instance.getEndpointStateForEndpoint(endpoint);
+ if (state.isAlive() && !Gossiper.instance.isDeadState(state))
+ Gossiper.instance.realMarkAlive(endpoint, state);
+ }
+
+ for (VersionedApplicationState value : newState)
+ {
+ ApplicationState as = toApplicationState(value);
+ VersionedValue vv = toVersionedValue(value);
+ state.addApplicationState(as, vv);
+ storageService.onChange(endpoint, as, vv);
+ }
+ });
+
+ MessagingService.instance().versions.set(endpoint, messagingVersion);
Review comment:
Can we remove this and rely on `NET_VERSION`? We get this for free if we add `NET_VERSION`.
##########
File path: test/distributed/org/apache/cassandra/distributed/action/GossipHelper.java
##########
@@ -0,0 +1,431 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.distributed.action;
+
+import java.io.IOException;
+import java.io.Serializable;
+import java.net.InetSocketAddress;
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.TimeUnit;
+import java.util.stream.Stream;
+
+import net.openhft.chronicle.core.util.SerializableBiFunction;
+import org.apache.cassandra.db.SystemKeyspace;
+import org.apache.cassandra.dht.IPartitioner;
+import org.apache.cassandra.dht.Token;
+import org.apache.cassandra.distributed.api.IInstance;
+import org.apache.cassandra.distributed.api.IInvokableInstance;
+import org.apache.cassandra.distributed.api.IIsolatedExecutor;
+import org.apache.cassandra.distributed.impl.Instance;
+import org.apache.cassandra.distributed.shared.VersionedApplicationState;
+import org.apache.cassandra.gms.ApplicationState;
+import org.apache.cassandra.gms.EndpointState;
+import org.apache.cassandra.gms.Gossiper;
+import org.apache.cassandra.gms.VersionedValue;
+import org.apache.cassandra.io.util.DataInputBuffer;
+import org.apache.cassandra.io.util.DataOutputBuffer;
+import org.apache.cassandra.locator.InetAddressAndPort;
+import org.apache.cassandra.locator.TokenMetadata;
+import org.apache.cassandra.net.MessagingService;
+import org.apache.cassandra.schema.MigrationManager;
+import org.apache.cassandra.service.PendingRangeCalculatorService;
+import org.apache.cassandra.service.StorageService;
+import org.apache.cassandra.utils.FBUtilities;
+
+import static org.apache.cassandra.distributed.impl.DistributedTestSnitch.toCassandraInetAddressAndPort;
+
+public class GossipHelper
+{
+ public static InstanceAction statusToBootstrap(IInvokableInstance newNode)
+ {
+ return (instance) ->
+ {
+ changeGossipState(instance,
+ newNode,
+ Arrays.asList(tokens(newNode),
+ statusBootstrapping(newNode),
+ statusWithPortBootstrapping(newNode)));
+ };
+ }
+
+ public static InstanceAction statusToNormal(IInvokableInstance peer)
+ {
+ return (target) ->
+ {
+ changeGossipState(target,
+ peer,
+ Arrays.asList(tokens(peer),
+ statusNormal(peer),
+ releaseVersion(peer),
+ statusWithPortNormal(peer)));
+ };
+ }
+
+ /**
+ * This method is unsafe and should be used _only_ when gossip is not used or available: it creates versioned values on the
+ * target instance, which means Gossip versioning gets out of sync. Use a safe couterpart at all times when performing _any_
+ * ring movement operations _or_ if Gossip is used.
+ */
+ public static InstanceAction unsafeStatusToNormal(IInstance peer)
+ {
+ return (target) ->
+ {
+ changeGossipState(target,
+ peer,
+ Arrays.asList(unsafeVersionedToken(target,
+ ApplicationState.TOKENS,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).tokens(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeVersionedToken(target,
+ ApplicationState.STATUS,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeVersionedToken(target,
+ ApplicationState.STATUS_WITH_PORT,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeReleaseVersion(target,
+ peer.config().getString("partitioner"),
+ peer.getReleaseVersionString())));
+ };
+ }
+
+ public static InstanceAction statusToLeaving(IInvokableInstance newNode)
+ {
+ return (instance) -> {
+ changeGossipState(instance,
+ newNode,
+ Arrays.asList(tokens(newNode),
+ statusLeaving(newNode),
+ statusWithPortLeaving(newNode)));
+ };
+ }
+
+ public static InstanceAction bootstrap()
+ {
+ return new BootstrapAction();
+ }
+
+ public static InstanceAction bootstrap(boolean joinRing, Duration waitForBootstrap, Duration waitForSchema)
+ {
+ return new BootstrapAction(joinRing, waitForBootstrap, waitForSchema);
+ }
+
+ public static InstanceAction disseminateGossipState(IInvokableInstance newNode)
+ {
+ return new DisseminateGossipState(newNode);
+ }
+
+ public static InstanceAction pullSchemaFrom(IInvokableInstance pullFrom)
+ {
+ return new PullSchemaFrom(pullFrom);
+ }
+
+ private static InstanceAction disableBinary()
+ {
+ return (instance) -> {
+ instance.runOnInstance(StorageService.instance::stopNativeTransport);
+ };
+ }
+
+ private static class DisseminateGossipState implements InstanceAction
+ {
+ final Map<InetSocketAddress, byte[]> gossipState;
+
+ public DisseminateGossipState(IInvokableInstance... from)
+ {
+ gossipState = new HashMap<>();
+ for (IInvokableInstance node : from)
+ {
+ byte[] epBytes = node.callsOnInstance(() -> {
+ EndpointState epState = Gossiper.instance.getEndpointStateForEndpoint(FBUtilities.getBroadcastAddressAndPort());
+ return toBytes(epState);
+ }).call();
+ gossipState.put(node.broadcastAddress(), epBytes);
+ }
+ }
+
+ public void accept(IInvokableInstance instance)
+ {
+ instance.appliesOnInstance((IIsolatedExecutor.SerializableFunction<Map<InetSocketAddress, byte[]>, Void>)
+ (map) -> {
+ Map<InetAddressAndPort, EndpointState> newState = new HashMap<>();
+ for (Map.Entry<InetSocketAddress, byte[]> e : map.entrySet())
+ newState.put(toCassandraInetAddressAndPort(e.getKey()), fromBytes(e.getValue()));
+
+ Gossiper.runInGossipStageBlocking(() -> {
+ Gossiper.instance.applyStateLocally(newState);
+ });
+ return null;
+ }).apply(gossipState);
+ }
+ }
+
+ public static byte[] toBytes(EndpointState epState)
+ {
+ try (DataOutputBuffer out = new DataOutputBuffer(1024))
+ {
+ EndpointState.serializer.serialize(epState, out, MessagingService.current_version);
+ return out.toByteArray();
+ }
+ catch (IOException e)
+ {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public static EndpointState fromBytes(byte[] bytes)
+ {
+ try (DataInputBuffer in = new DataInputBuffer(bytes))
+ {
+ return EndpointState.serializer.deserialize(in, MessagingService.current_version);
+ }
+ catch (Throwable t)
+ {
+ throw new RuntimeException(t);
+ }
+ }
+
+ private static class PullSchemaFrom implements InstanceAction
+ {
+ final InetSocketAddress pullFrom;
+
+ public PullSchemaFrom(IInvokableInstance pullFrom)
+ {
+ this.pullFrom = pullFrom.broadcastAddress();;
+ }
+
+ public void accept(IInvokableInstance pullTo)
+ {
+ pullTo.acceptsOnInstance((InetSocketAddress pullFrom) -> {
+ InetAddressAndPort endpoint = toCassandraInetAddressAndPort(pullFrom);
+ EndpointState state = Gossiper.instance.getEndpointStateForEndpoint(endpoint);
+ MigrationManager.scheduleSchemaPull(endpoint, state);
+ MigrationManager.waitUntilReadyForBootstrap();
+ }).accept(pullFrom);
+ }
+ }
+
+ private static class BootstrapAction implements InstanceAction, Serializable
+ {
+ private final boolean joinRing;
+ private final Duration waitForBootstrap;
+ private final Duration waitForSchema;
+
+ public BootstrapAction()
+ {
+ this(true, Duration.ofMinutes(10), Duration.ofSeconds(10));
+ }
+
+ public BootstrapAction(boolean joinRing, Duration waitForBootstrap, Duration waitForSchema)
+ {
+ this.joinRing = joinRing;
+ this.waitForBootstrap = waitForBootstrap;
+ this.waitForSchema = waitForSchema;
+ }
+
+ public void accept(IInvokableInstance instance)
+ {
+ instance.appliesOnInstance((String partitionerString, String tokenString) -> {
+ IPartitioner partitioner = FBUtilities.newPartitioner(partitionerString);
+ List<Token> tokens = Collections.singletonList(partitioner.getTokenFactory().fromString(tokenString));
+ try
+ {
+ SystemKeyspace.setBootstrapState(SystemKeyspace.BootstrapState.IN_PROGRESS);
+ StorageService.instance.waitForSchema((int) waitForSchema.toMillis());
+ PendingRangeCalculatorService.instance.blockUntilFinished();
+ StorageService.instance.startBootstrap(tokens).get(waitForBootstrap.toMillis(), TimeUnit.MILLISECONDS);
+ StorageService.instance.setUpDistributedSystemKeyspaces();
+ if (joinRing)
+ StorageService.instance.finishJoiningRing(true, tokens);
+ }
+ catch (Throwable t)
+ {
+ throw new RuntimeException(t);
+ }
+
+ return null;
+ }).apply(instance.config().getString("partitioner"), instance.config().getString("initial_token"));
+ }
+ }
+
+ public static InstanceAction decomission()
+ {
+ return (target) -> {
+ target.runOnInstance(() -> {
+ try
+ {
+ StorageService.instance.decommission(false);
+ }
+ catch (InterruptedException e)
+ {
+ throw new RuntimeException();
+ }
+ });
+ };
+ }
+
+
+ public static VersionedApplicationState tokens(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.TOKENS, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).tokens(tokens));
+ }
+
+ public static VersionedApplicationState unsafeReleaseVersion(IInvokableInstance instance, String partitionerStr, String releaseVersionStr)
+ {
+ return instance.appliesOnInstance((String partitionerString, String releaseVersion) -> {
+ IPartitioner partitioner = FBUtilities.newPartitioner(partitionerString);
+ VersionedValue versionedValue = new VersionedValue.VersionedValueFactory(partitioner).releaseVersion(releaseVersion);
+ return new VersionedApplicationState(ApplicationState.RELEASE_VERSION.ordinal(), versionedValue.value, versionedValue.version);
+ }).apply(partitionerStr, releaseVersionStr);
+ }
+
+ public static VersionedApplicationState releaseVersion(IInvokableInstance instance)
+ {
+ return unsafeReleaseVersion(instance, instance.config().getString("partitioner"), instance.getReleaseVersionString());
+ }
+
+ public static VersionedApplicationState statusNormal(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens));
+ }
+
+ public static VersionedApplicationState statusWithPortNormal(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS_WITH_PORT, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens));
+ }
+
+ public static VersionedApplicationState statusBootstrapping(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).bootstrapping(tokens));
+ }
+
+ public static VersionedApplicationState statusWithPortBootstrapping(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS_WITH_PORT, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).bootstrapping(tokens));
+ }
+
+ public static VersionedApplicationState statusLeaving(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).leaving(tokens));
+ }
+
+ public static VersionedApplicationState statusWithPortLeaving(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS_WITH_PORT, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).leaving(tokens));
+ }
+
+ public static VersionedValue toVersionedValue(VersionedApplicationState vv)
+ {
+ return VersionedValue.unsafeMakeVersionedValue(vv.value, vv.version);
+ }
+
+ public static ApplicationState toApplicationState(VersionedApplicationState vv)
+ {
+ return ApplicationState.values()[vv.applicationState];
+ }
+
+ public static VersionedApplicationState unsafeVersionedToken(IInvokableInstance instance,
+ ApplicationState applicationState,
+ SerializableBiFunction<IPartitioner, Collection<Token>, VersionedValue> supplier,
+ String partitionerStr, String initialTokenStr)
+ {
+ return instance.appliesOnInstance((String partitionerString, String tokenString) -> {
+ IPartitioner partitioner = FBUtilities.newPartitioner(partitionerString);
+ Token token = partitioner.getTokenFactory().fromString(tokenString);
+
+ VersionedValue versionedValue = supplier.apply(partitioner, Collections.singleton(token));
+ return new VersionedApplicationState(applicationState.ordinal(), versionedValue.value, versionedValue.version);
+ }).apply(partitionerStr, initialTokenStr);
+ }
+
+ public static VersionedApplicationState versionedToken(IInvokableInstance instance, ApplicationState applicationState, SerializableBiFunction<IPartitioner, Collection<Token>, VersionedValue> supplier)
Review comment:
private?
##########
File path: test/distributed/org/apache/cassandra/distributed/action/GossipHelper.java
##########
@@ -0,0 +1,431 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.distributed.action;
+
+import java.io.IOException;
+import java.io.Serializable;
+import java.net.InetSocketAddress;
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.TimeUnit;
+import java.util.stream.Stream;
+
+import net.openhft.chronicle.core.util.SerializableBiFunction;
+import org.apache.cassandra.db.SystemKeyspace;
+import org.apache.cassandra.dht.IPartitioner;
+import org.apache.cassandra.dht.Token;
+import org.apache.cassandra.distributed.api.IInstance;
+import org.apache.cassandra.distributed.api.IInvokableInstance;
+import org.apache.cassandra.distributed.api.IIsolatedExecutor;
+import org.apache.cassandra.distributed.impl.Instance;
+import org.apache.cassandra.distributed.shared.VersionedApplicationState;
+import org.apache.cassandra.gms.ApplicationState;
+import org.apache.cassandra.gms.EndpointState;
+import org.apache.cassandra.gms.Gossiper;
+import org.apache.cassandra.gms.VersionedValue;
+import org.apache.cassandra.io.util.DataInputBuffer;
+import org.apache.cassandra.io.util.DataOutputBuffer;
+import org.apache.cassandra.locator.InetAddressAndPort;
+import org.apache.cassandra.locator.TokenMetadata;
+import org.apache.cassandra.net.MessagingService;
+import org.apache.cassandra.schema.MigrationManager;
+import org.apache.cassandra.service.PendingRangeCalculatorService;
+import org.apache.cassandra.service.StorageService;
+import org.apache.cassandra.utils.FBUtilities;
+
+import static org.apache.cassandra.distributed.impl.DistributedTestSnitch.toCassandraInetAddressAndPort;
+
+public class GossipHelper
+{
+ public static InstanceAction statusToBootstrap(IInvokableInstance newNode)
+ {
+ return (instance) ->
+ {
+ changeGossipState(instance,
+ newNode,
+ Arrays.asList(tokens(newNode),
+ statusBootstrapping(newNode),
+ statusWithPortBootstrapping(newNode)));
+ };
+ }
+
+ public static InstanceAction statusToNormal(IInvokableInstance peer)
+ {
+ return (target) ->
+ {
+ changeGossipState(target,
+ peer,
+ Arrays.asList(tokens(peer),
+ statusNormal(peer),
+ releaseVersion(peer),
+ statusWithPortNormal(peer)));
+ };
+ }
+
+ /**
+ * This method is unsafe and should be used _only_ when gossip is not used or available: it creates versioned values on the
+ * target instance, which means Gossip versioning gets out of sync. Use a safe couterpart at all times when performing _any_
+ * ring movement operations _or_ if Gossip is used.
+ */
+ public static InstanceAction unsafeStatusToNormal(IInstance peer)
+ {
+ return (target) ->
+ {
+ changeGossipState(target,
+ peer,
+ Arrays.asList(unsafeVersionedToken(target,
+ ApplicationState.TOKENS,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).tokens(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeVersionedToken(target,
+ ApplicationState.STATUS,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeVersionedToken(target,
+ ApplicationState.STATUS_WITH_PORT,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeReleaseVersion(target,
+ peer.config().getString("partitioner"),
+ peer.getReleaseVersionString())));
+ };
+ }
+
+ public static InstanceAction statusToLeaving(IInvokableInstance newNode)
+ {
+ return (instance) -> {
+ changeGossipState(instance,
+ newNode,
+ Arrays.asList(tokens(newNode),
+ statusLeaving(newNode),
+ statusWithPortLeaving(newNode)));
+ };
+ }
+
+ public static InstanceAction bootstrap()
+ {
+ return new BootstrapAction();
+ }
+
+ public static InstanceAction bootstrap(boolean joinRing, Duration waitForBootstrap, Duration waitForSchema)
+ {
+ return new BootstrapAction(joinRing, waitForBootstrap, waitForSchema);
+ }
+
+ public static InstanceAction disseminateGossipState(IInvokableInstance newNode)
+ {
+ return new DisseminateGossipState(newNode);
+ }
+
+ public static InstanceAction pullSchemaFrom(IInvokableInstance pullFrom)
+ {
+ return new PullSchemaFrom(pullFrom);
+ }
+
+ private static InstanceAction disableBinary()
+ {
+ return (instance) -> {
+ instance.runOnInstance(StorageService.instance::stopNativeTransport);
+ };
+ }
+
+ private static class DisseminateGossipState implements InstanceAction
+ {
+ final Map<InetSocketAddress, byte[]> gossipState;
+
+ public DisseminateGossipState(IInvokableInstance... from)
+ {
+ gossipState = new HashMap<>();
+ for (IInvokableInstance node : from)
+ {
+ byte[] epBytes = node.callsOnInstance(() -> {
+ EndpointState epState = Gossiper.instance.getEndpointStateForEndpoint(FBUtilities.getBroadcastAddressAndPort());
+ return toBytes(epState);
+ }).call();
+ gossipState.put(node.broadcastAddress(), epBytes);
+ }
+ }
+
+ public void accept(IInvokableInstance instance)
+ {
+ instance.appliesOnInstance((IIsolatedExecutor.SerializableFunction<Map<InetSocketAddress, byte[]>, Void>)
+ (map) -> {
+ Map<InetAddressAndPort, EndpointState> newState = new HashMap<>();
+ for (Map.Entry<InetSocketAddress, byte[]> e : map.entrySet())
+ newState.put(toCassandraInetAddressAndPort(e.getKey()), fromBytes(e.getValue()));
+
+ Gossiper.runInGossipStageBlocking(() -> {
+ Gossiper.instance.applyStateLocally(newState);
+ });
+ return null;
+ }).apply(gossipState);
+ }
+ }
+
+ public static byte[] toBytes(EndpointState epState)
+ {
+ try (DataOutputBuffer out = new DataOutputBuffer(1024))
+ {
+ EndpointState.serializer.serialize(epState, out, MessagingService.current_version);
+ return out.toByteArray();
+ }
+ catch (IOException e)
+ {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public static EndpointState fromBytes(byte[] bytes)
+ {
+ try (DataInputBuffer in = new DataInputBuffer(bytes))
+ {
+ return EndpointState.serializer.deserialize(in, MessagingService.current_version);
+ }
+ catch (Throwable t)
+ {
+ throw new RuntimeException(t);
+ }
+ }
+
+ private static class PullSchemaFrom implements InstanceAction
+ {
+ final InetSocketAddress pullFrom;
+
+ public PullSchemaFrom(IInvokableInstance pullFrom)
+ {
+ this.pullFrom = pullFrom.broadcastAddress();;
+ }
+
+ public void accept(IInvokableInstance pullTo)
+ {
+ pullTo.acceptsOnInstance((InetSocketAddress pullFrom) -> {
+ InetAddressAndPort endpoint = toCassandraInetAddressAndPort(pullFrom);
+ EndpointState state = Gossiper.instance.getEndpointStateForEndpoint(endpoint);
+ MigrationManager.scheduleSchemaPull(endpoint, state);
+ MigrationManager.waitUntilReadyForBootstrap();
+ }).accept(pullFrom);
+ }
+ }
+
+ private static class BootstrapAction implements InstanceAction, Serializable
+ {
+ private final boolean joinRing;
+ private final Duration waitForBootstrap;
+ private final Duration waitForSchema;
+
+ public BootstrapAction()
+ {
+ this(true, Duration.ofMinutes(10), Duration.ofSeconds(10));
+ }
+
+ public BootstrapAction(boolean joinRing, Duration waitForBootstrap, Duration waitForSchema)
+ {
+ this.joinRing = joinRing;
+ this.waitForBootstrap = waitForBootstrap;
+ this.waitForSchema = waitForSchema;
+ }
+
+ public void accept(IInvokableInstance instance)
+ {
+ instance.appliesOnInstance((String partitionerString, String tokenString) -> {
+ IPartitioner partitioner = FBUtilities.newPartitioner(partitionerString);
+ List<Token> tokens = Collections.singletonList(partitioner.getTokenFactory().fromString(tokenString));
+ try
+ {
+ SystemKeyspace.setBootstrapState(SystemKeyspace.BootstrapState.IN_PROGRESS);
+ StorageService.instance.waitForSchema((int) waitForSchema.toMillis());
+ PendingRangeCalculatorService.instance.blockUntilFinished();
+ StorageService.instance.startBootstrap(tokens).get(waitForBootstrap.toMillis(), TimeUnit.MILLISECONDS);
+ StorageService.instance.setUpDistributedSystemKeyspaces();
+ if (joinRing)
+ StorageService.instance.finishJoiningRing(true, tokens);
+ }
+ catch (Throwable t)
+ {
+ throw new RuntimeException(t);
+ }
+
+ return null;
+ }).apply(instance.config().getString("partitioner"), instance.config().getString("initial_token"));
+ }
+ }
+
+ public static InstanceAction decomission()
+ {
+ return (target) -> {
+ target.runOnInstance(() -> {
+ try
+ {
+ StorageService.instance.decommission(false);
+ }
+ catch (InterruptedException e)
+ {
+ throw new RuntimeException();
+ }
+ });
+ };
+ }
+
+
+ public static VersionedApplicationState tokens(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.TOKENS, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).tokens(tokens));
+ }
+
+ public static VersionedApplicationState unsafeReleaseVersion(IInvokableInstance instance, String partitionerStr, String releaseVersionStr)
+ {
+ return instance.appliesOnInstance((String partitionerString, String releaseVersion) -> {
+ IPartitioner partitioner = FBUtilities.newPartitioner(partitionerString);
+ VersionedValue versionedValue = new VersionedValue.VersionedValueFactory(partitioner).releaseVersion(releaseVersion);
+ return new VersionedApplicationState(ApplicationState.RELEASE_VERSION.ordinal(), versionedValue.value, versionedValue.version);
+ }).apply(partitionerStr, releaseVersionStr);
+ }
+
+ public static VersionedApplicationState releaseVersion(IInvokableInstance instance)
+ {
+ return unsafeReleaseVersion(instance, instance.config().getString("partitioner"), instance.getReleaseVersionString());
+ }
+
+ public static VersionedApplicationState statusNormal(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens));
+ }
+
+ public static VersionedApplicationState statusWithPortNormal(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS_WITH_PORT, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens));
+ }
+
+ public static VersionedApplicationState statusBootstrapping(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).bootstrapping(tokens));
+ }
+
+ public static VersionedApplicationState statusWithPortBootstrapping(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS_WITH_PORT, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).bootstrapping(tokens));
+ }
+
+ public static VersionedApplicationState statusLeaving(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).leaving(tokens));
+ }
+
+ public static VersionedApplicationState statusWithPortLeaving(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS_WITH_PORT, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).leaving(tokens));
+ }
+
+ public static VersionedValue toVersionedValue(VersionedApplicationState vv)
+ {
+ return VersionedValue.unsafeMakeVersionedValue(vv.value, vv.version);
+ }
+
+ public static ApplicationState toApplicationState(VersionedApplicationState vv)
+ {
+ return ApplicationState.values()[vv.applicationState];
+ }
+
+ public static VersionedApplicationState unsafeVersionedToken(IInvokableInstance instance,
+ ApplicationState applicationState,
+ SerializableBiFunction<IPartitioner, Collection<Token>, VersionedValue> supplier,
+ String partitionerStr, String initialTokenStr)
+ {
+ return instance.appliesOnInstance((String partitionerString, String tokenString) -> {
+ IPartitioner partitioner = FBUtilities.newPartitioner(partitionerString);
+ Token token = partitioner.getTokenFactory().fromString(tokenString);
+
+ VersionedValue versionedValue = supplier.apply(partitioner, Collections.singleton(token));
+ return new VersionedApplicationState(applicationState.ordinal(), versionedValue.value, versionedValue.version);
+ }).apply(partitionerStr, initialTokenStr);
+ }
+
+ public static VersionedApplicationState versionedToken(IInvokableInstance instance, ApplicationState applicationState, SerializableBiFunction<IPartitioner, Collection<Token>, VersionedValue> supplier)
+ {
+ return unsafeVersionedToken(instance, applicationState, supplier, instance.config().getString("partitioner"), instance.config().getString("initial_token"));
+ }
+
+ public void removeFromRing(IInstance peer)
+ {
+ InetAddressAndPort endpoint = toCassandraInetAddressAndPort(peer.broadcastAddress());
+
+ TokenMetadata tokenMetadata = StorageService.instance.getTokenMetadata();
+ tokenMetadata.removeEndpoint(endpoint);
+ Collection<Token> tokens = tokenMetadata.getTokens(endpoint);
+ if (!tokens.isEmpty())
+ tokenMetadata.removeBootstrapTokens(tokens);
+
+ Gossiper.runInGossipStageBlocking(() -> Gossiper.instance.unsafeAnulEndpoint(endpoint));
+
+ SystemKeyspace.removeEndpoint(endpoint);
+ PendingRangeCalculatorService.instance.update();
+ PendingRangeCalculatorService.instance.blockUntilFinished();
+ }
+
+ public static void changeGossipState(Stream<IInvokableInstance> targets, Instance peer, List<VersionedApplicationState> newState)
+ {
+ targets.forEach((instance) -> {
+ changeGossipState(instance, peer, newState);
+ });
+ }
+
+ /**
+ * Changes gossip state of the `peer` on `target`
+ */
+ public static void changeGossipState(IInvokableInstance target, IInstance peer, List<VersionedApplicationState> newState)
+ {
+ int version = peer.isShutdown() ? MessagingService.current_version : peer.getMessagingVersion();
+
+ target.appliesOnInstance((InetSocketAddress addr, UUID hostId, Integer messagingVersion) -> {
+ InetAddressAndPort endpoint = toCassandraInetAddressAndPort(addr);
+ StorageService storageService = StorageService.instance;
+
+ Gossiper.runInGossipStageBlocking(() -> {
+ EndpointState state = Gossiper.instance.getEndpointStateForEndpoint(endpoint);
+ if (state == null)
+ {
+ Gossiper.instance.initializeNodeUnsafe(endpoint, hostId, 1);
Review comment:
this sets `ApplicationState.NET_VERSION` to target's version rather than the peer's, should this be updated to take `version`?
##########
File path: test/distributed/org/apache/cassandra/distributed/impl/Instance.java
##########
@@ -467,17 +465,23 @@ public void startup(ICluster cluster)
StorageService.instance.registerDaemon(CassandraDaemon.getInstanceForTesting());
if (config.has(GOSSIP))
{
+ MigrationManager.setUptimeFn(() -> TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startedAt));
StorageService.instance.initServer();
StorageService.instance.removeShutdownHook();
Gossiper.waitToSettle();
}
else
{
- initializeRing(cluster);
+ cluster.stream().forEach(peer -> {
+ if (peer instanceof IInvokableInstance)
+ GossipHelper.statusToNormal((IInvokableInstance) peer).accept(this);
+ else
+ GossipHelper.unsafeStatusToNormal((IInstance) peer).accept(this);
Review comment:
we don't need to worry about this case, as cluster can only have `IInvokableInstance`; we can simplify this to
```
assert peer instanceof IInvokableInstance : "Peer is not a IInvokableInstance";
GossipHelper.statusToNormal((IInvokableInstance) peer).accept(this);
```
##########
File path: test/distributed/org/apache/cassandra/distributed/action/GossipHelper.java
##########
@@ -0,0 +1,431 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.distributed.action;
+
+import java.io.IOException;
+import java.io.Serializable;
+import java.net.InetSocketAddress;
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.TimeUnit;
+import java.util.stream.Stream;
+
+import net.openhft.chronicle.core.util.SerializableBiFunction;
+import org.apache.cassandra.db.SystemKeyspace;
+import org.apache.cassandra.dht.IPartitioner;
+import org.apache.cassandra.dht.Token;
+import org.apache.cassandra.distributed.api.IInstance;
+import org.apache.cassandra.distributed.api.IInvokableInstance;
+import org.apache.cassandra.distributed.api.IIsolatedExecutor;
+import org.apache.cassandra.distributed.impl.Instance;
+import org.apache.cassandra.distributed.shared.VersionedApplicationState;
+import org.apache.cassandra.gms.ApplicationState;
+import org.apache.cassandra.gms.EndpointState;
+import org.apache.cassandra.gms.Gossiper;
+import org.apache.cassandra.gms.VersionedValue;
+import org.apache.cassandra.io.util.DataInputBuffer;
+import org.apache.cassandra.io.util.DataOutputBuffer;
+import org.apache.cassandra.locator.InetAddressAndPort;
+import org.apache.cassandra.locator.TokenMetadata;
+import org.apache.cassandra.net.MessagingService;
+import org.apache.cassandra.schema.MigrationManager;
+import org.apache.cassandra.service.PendingRangeCalculatorService;
+import org.apache.cassandra.service.StorageService;
+import org.apache.cassandra.utils.FBUtilities;
+
+import static org.apache.cassandra.distributed.impl.DistributedTestSnitch.toCassandraInetAddressAndPort;
+
+public class GossipHelper
+{
+ public static InstanceAction statusToBootstrap(IInvokableInstance newNode)
+ {
+ return (instance) ->
+ {
+ changeGossipState(instance,
+ newNode,
+ Arrays.asList(tokens(newNode),
+ statusBootstrapping(newNode),
+ statusWithPortBootstrapping(newNode)));
+ };
+ }
+
+ public static InstanceAction statusToNormal(IInvokableInstance peer)
+ {
+ return (target) ->
+ {
+ changeGossipState(target,
+ peer,
+ Arrays.asList(tokens(peer),
+ statusNormal(peer),
+ releaseVersion(peer),
+ statusWithPortNormal(peer)));
+ };
+ }
+
+ /**
+ * This method is unsafe and should be used _only_ when gossip is not used or available: it creates versioned values on the
+ * target instance, which means Gossip versioning gets out of sync. Use a safe couterpart at all times when performing _any_
+ * ring movement operations _or_ if Gossip is used.
+ */
+ public static InstanceAction unsafeStatusToNormal(IInstance peer)
+ {
+ return (target) ->
+ {
+ changeGossipState(target,
+ peer,
+ Arrays.asList(unsafeVersionedToken(target,
+ ApplicationState.TOKENS,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).tokens(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeVersionedToken(target,
+ ApplicationState.STATUS,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeVersionedToken(target,
+ ApplicationState.STATUS_WITH_PORT,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeReleaseVersion(target,
+ peer.config().getString("partitioner"),
+ peer.getReleaseVersionString())));
+ };
+ }
+
+ public static InstanceAction statusToLeaving(IInvokableInstance newNode)
+ {
+ return (instance) -> {
+ changeGossipState(instance,
+ newNode,
+ Arrays.asList(tokens(newNode),
+ statusLeaving(newNode),
+ statusWithPortLeaving(newNode)));
+ };
+ }
+
+ public static InstanceAction bootstrap()
+ {
+ return new BootstrapAction();
+ }
+
+ public static InstanceAction bootstrap(boolean joinRing, Duration waitForBootstrap, Duration waitForSchema)
+ {
+ return new BootstrapAction(joinRing, waitForBootstrap, waitForSchema);
+ }
+
+ public static InstanceAction disseminateGossipState(IInvokableInstance newNode)
+ {
+ return new DisseminateGossipState(newNode);
+ }
+
+ public static InstanceAction pullSchemaFrom(IInvokableInstance pullFrom)
+ {
+ return new PullSchemaFrom(pullFrom);
+ }
+
+ private static InstanceAction disableBinary()
+ {
+ return (instance) -> {
+ instance.runOnInstance(StorageService.instance::stopNativeTransport);
+ };
+ }
+
+ private static class DisseminateGossipState implements InstanceAction
+ {
+ final Map<InetSocketAddress, byte[]> gossipState;
+
+ public DisseminateGossipState(IInvokableInstance... from)
+ {
+ gossipState = new HashMap<>();
+ for (IInvokableInstance node : from)
+ {
+ byte[] epBytes = node.callsOnInstance(() -> {
+ EndpointState epState = Gossiper.instance.getEndpointStateForEndpoint(FBUtilities.getBroadcastAddressAndPort());
+ return toBytes(epState);
+ }).call();
+ gossipState.put(node.broadcastAddress(), epBytes);
+ }
+ }
+
+ public void accept(IInvokableInstance instance)
+ {
+ instance.appliesOnInstance((IIsolatedExecutor.SerializableFunction<Map<InetSocketAddress, byte[]>, Void>)
+ (map) -> {
+ Map<InetAddressAndPort, EndpointState> newState = new HashMap<>();
+ for (Map.Entry<InetSocketAddress, byte[]> e : map.entrySet())
+ newState.put(toCassandraInetAddressAndPort(e.getKey()), fromBytes(e.getValue()));
+
+ Gossiper.runInGossipStageBlocking(() -> {
+ Gossiper.instance.applyStateLocally(newState);
+ });
+ return null;
+ }).apply(gossipState);
+ }
+ }
+
+ public static byte[] toBytes(EndpointState epState)
+ {
+ try (DataOutputBuffer out = new DataOutputBuffer(1024))
+ {
+ EndpointState.serializer.serialize(epState, out, MessagingService.current_version);
+ return out.toByteArray();
+ }
+ catch (IOException e)
+ {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public static EndpointState fromBytes(byte[] bytes)
+ {
+ try (DataInputBuffer in = new DataInputBuffer(bytes))
+ {
+ return EndpointState.serializer.deserialize(in, MessagingService.current_version);
+ }
+ catch (Throwable t)
+ {
+ throw new RuntimeException(t);
+ }
+ }
+
+ private static class PullSchemaFrom implements InstanceAction
+ {
+ final InetSocketAddress pullFrom;
+
+ public PullSchemaFrom(IInvokableInstance pullFrom)
+ {
+ this.pullFrom = pullFrom.broadcastAddress();;
+ }
+
+ public void accept(IInvokableInstance pullTo)
+ {
+ pullTo.acceptsOnInstance((InetSocketAddress pullFrom) -> {
+ InetAddressAndPort endpoint = toCassandraInetAddressAndPort(pullFrom);
+ EndpointState state = Gossiper.instance.getEndpointStateForEndpoint(endpoint);
+ MigrationManager.scheduleSchemaPull(endpoint, state);
+ MigrationManager.waitUntilReadyForBootstrap();
+ }).accept(pullFrom);
+ }
+ }
+
+ private static class BootstrapAction implements InstanceAction, Serializable
+ {
+ private final boolean joinRing;
+ private final Duration waitForBootstrap;
+ private final Duration waitForSchema;
+
+ public BootstrapAction()
+ {
+ this(true, Duration.ofMinutes(10), Duration.ofSeconds(10));
+ }
+
+ public BootstrapAction(boolean joinRing, Duration waitForBootstrap, Duration waitForSchema)
+ {
+ this.joinRing = joinRing;
+ this.waitForBootstrap = waitForBootstrap;
+ this.waitForSchema = waitForSchema;
+ }
+
+ public void accept(IInvokableInstance instance)
+ {
+ instance.appliesOnInstance((String partitionerString, String tokenString) -> {
Review comment:
I feel that it would be best to refactor https://github.com/apache/cassandra/blob/trunk/src/java/org/apache/cassandra/service/StorageService.java#L907-L991 to make this a function, and just call that. This logic is a simplification of that logic and is likely to drift over time as people change `joinTokenRing`; it would be more maintainable if we reused the same logic rather than rewrite.
It also allows for usages like bootstrap for replacement, as this logic doesn't support it but would if this unified with `joinTokenRing`.
##########
File path: test/distributed/org/apache/cassandra/distributed/action/GossipHelper.java
##########
@@ -0,0 +1,431 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.distributed.action;
+
+import java.io.IOException;
+import java.io.Serializable;
+import java.net.InetSocketAddress;
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.TimeUnit;
+import java.util.stream.Stream;
+
+import net.openhft.chronicle.core.util.SerializableBiFunction;
+import org.apache.cassandra.db.SystemKeyspace;
+import org.apache.cassandra.dht.IPartitioner;
+import org.apache.cassandra.dht.Token;
+import org.apache.cassandra.distributed.api.IInstance;
+import org.apache.cassandra.distributed.api.IInvokableInstance;
+import org.apache.cassandra.distributed.api.IIsolatedExecutor;
+import org.apache.cassandra.distributed.impl.Instance;
+import org.apache.cassandra.distributed.shared.VersionedApplicationState;
+import org.apache.cassandra.gms.ApplicationState;
+import org.apache.cassandra.gms.EndpointState;
+import org.apache.cassandra.gms.Gossiper;
+import org.apache.cassandra.gms.VersionedValue;
+import org.apache.cassandra.io.util.DataInputBuffer;
+import org.apache.cassandra.io.util.DataOutputBuffer;
+import org.apache.cassandra.locator.InetAddressAndPort;
+import org.apache.cassandra.locator.TokenMetadata;
+import org.apache.cassandra.net.MessagingService;
+import org.apache.cassandra.schema.MigrationManager;
+import org.apache.cassandra.service.PendingRangeCalculatorService;
+import org.apache.cassandra.service.StorageService;
+import org.apache.cassandra.utils.FBUtilities;
+
+import static org.apache.cassandra.distributed.impl.DistributedTestSnitch.toCassandraInetAddressAndPort;
+
+public class GossipHelper
+{
+ public static InstanceAction statusToBootstrap(IInvokableInstance newNode)
+ {
+ return (instance) ->
+ {
+ changeGossipState(instance,
+ newNode,
+ Arrays.asList(tokens(newNode),
+ statusBootstrapping(newNode),
+ statusWithPortBootstrapping(newNode)));
+ };
+ }
+
+ public static InstanceAction statusToNormal(IInvokableInstance peer)
+ {
+ return (target) ->
+ {
+ changeGossipState(target,
+ peer,
+ Arrays.asList(tokens(peer),
+ statusNormal(peer),
+ releaseVersion(peer),
+ statusWithPortNormal(peer)));
+ };
+ }
+
+ /**
+ * This method is unsafe and should be used _only_ when gossip is not used or available: it creates versioned values on the
+ * target instance, which means Gossip versioning gets out of sync. Use a safe couterpart at all times when performing _any_
+ * ring movement operations _or_ if Gossip is used.
+ */
+ public static InstanceAction unsafeStatusToNormal(IInstance peer)
+ {
+ return (target) ->
+ {
+ changeGossipState(target,
+ peer,
+ Arrays.asList(unsafeVersionedToken(target,
+ ApplicationState.TOKENS,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).tokens(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeVersionedToken(target,
+ ApplicationState.STATUS,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeVersionedToken(target,
+ ApplicationState.STATUS_WITH_PORT,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeReleaseVersion(target,
+ peer.config().getString("partitioner"),
+ peer.getReleaseVersionString())));
+ };
+ }
+
+ public static InstanceAction statusToLeaving(IInvokableInstance newNode)
+ {
+ return (instance) -> {
+ changeGossipState(instance,
+ newNode,
+ Arrays.asList(tokens(newNode),
+ statusLeaving(newNode),
+ statusWithPortLeaving(newNode)));
+ };
+ }
+
+ public static InstanceAction bootstrap()
+ {
+ return new BootstrapAction();
+ }
+
+ public static InstanceAction bootstrap(boolean joinRing, Duration waitForBootstrap, Duration waitForSchema)
+ {
+ return new BootstrapAction(joinRing, waitForBootstrap, waitForSchema);
+ }
+
+ public static InstanceAction disseminateGossipState(IInvokableInstance newNode)
+ {
+ return new DisseminateGossipState(newNode);
+ }
+
+ public static InstanceAction pullSchemaFrom(IInvokableInstance pullFrom)
+ {
+ return new PullSchemaFrom(pullFrom);
+ }
+
+ private static InstanceAction disableBinary()
+ {
+ return (instance) -> {
+ instance.runOnInstance(StorageService.instance::stopNativeTransport);
+ };
+ }
+
+ private static class DisseminateGossipState implements InstanceAction
+ {
+ final Map<InetSocketAddress, byte[]> gossipState;
+
+ public DisseminateGossipState(IInvokableInstance... from)
+ {
+ gossipState = new HashMap<>();
+ for (IInvokableInstance node : from)
+ {
+ byte[] epBytes = node.callsOnInstance(() -> {
+ EndpointState epState = Gossiper.instance.getEndpointStateForEndpoint(FBUtilities.getBroadcastAddressAndPort());
+ return toBytes(epState);
+ }).call();
+ gossipState.put(node.broadcastAddress(), epBytes);
+ }
+ }
+
+ public void accept(IInvokableInstance instance)
+ {
+ instance.appliesOnInstance((IIsolatedExecutor.SerializableFunction<Map<InetSocketAddress, byte[]>, Void>)
+ (map) -> {
+ Map<InetAddressAndPort, EndpointState> newState = new HashMap<>();
+ for (Map.Entry<InetSocketAddress, byte[]> e : map.entrySet())
+ newState.put(toCassandraInetAddressAndPort(e.getKey()), fromBytes(e.getValue()));
+
+ Gossiper.runInGossipStageBlocking(() -> {
+ Gossiper.instance.applyStateLocally(newState);
+ });
+ return null;
+ }).apply(gossipState);
+ }
+ }
+
+ public static byte[] toBytes(EndpointState epState)
+ {
+ try (DataOutputBuffer out = new DataOutputBuffer(1024))
+ {
+ EndpointState.serializer.serialize(epState, out, MessagingService.current_version);
+ return out.toByteArray();
+ }
+ catch (IOException e)
+ {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public static EndpointState fromBytes(byte[] bytes)
+ {
+ try (DataInputBuffer in = new DataInputBuffer(bytes))
+ {
+ return EndpointState.serializer.deserialize(in, MessagingService.current_version);
+ }
+ catch (Throwable t)
+ {
+ throw new RuntimeException(t);
+ }
+ }
+
+ private static class PullSchemaFrom implements InstanceAction
+ {
+ final InetSocketAddress pullFrom;
+
+ public PullSchemaFrom(IInvokableInstance pullFrom)
+ {
+ this.pullFrom = pullFrom.broadcastAddress();;
+ }
+
+ public void accept(IInvokableInstance pullTo)
+ {
+ pullTo.acceptsOnInstance((InetSocketAddress pullFrom) -> {
+ InetAddressAndPort endpoint = toCassandraInetAddressAndPort(pullFrom);
+ EndpointState state = Gossiper.instance.getEndpointStateForEndpoint(endpoint);
+ MigrationManager.scheduleSchemaPull(endpoint, state);
+ MigrationManager.waitUntilReadyForBootstrap();
+ }).accept(pullFrom);
+ }
+ }
+
+ private static class BootstrapAction implements InstanceAction, Serializable
+ {
+ private final boolean joinRing;
+ private final Duration waitForBootstrap;
+ private final Duration waitForSchema;
+
+ public BootstrapAction()
+ {
+ this(true, Duration.ofMinutes(10), Duration.ofSeconds(10));
+ }
+
+ public BootstrapAction(boolean joinRing, Duration waitForBootstrap, Duration waitForSchema)
+ {
+ this.joinRing = joinRing;
+ this.waitForBootstrap = waitForBootstrap;
+ this.waitForSchema = waitForSchema;
+ }
+
+ public void accept(IInvokableInstance instance)
+ {
+ instance.appliesOnInstance((String partitionerString, String tokenString) -> {
+ IPartitioner partitioner = FBUtilities.newPartitioner(partitionerString);
+ List<Token> tokens = Collections.singletonList(partitioner.getTokenFactory().fromString(tokenString));
+ try
+ {
+ SystemKeyspace.setBootstrapState(SystemKeyspace.BootstrapState.IN_PROGRESS);
+ StorageService.instance.waitForSchema((int) waitForSchema.toMillis());
+ PendingRangeCalculatorService.instance.blockUntilFinished();
+ StorageService.instance.startBootstrap(tokens).get(waitForBootstrap.toMillis(), TimeUnit.MILLISECONDS);
+ StorageService.instance.setUpDistributedSystemKeyspaces();
+ if (joinRing)
+ StorageService.instance.finishJoiningRing(true, tokens);
+ }
+ catch (Throwable t)
+ {
+ throw new RuntimeException(t);
+ }
+
+ return null;
+ }).apply(instance.config().getString("partitioner"), instance.config().getString("initial_token"));
+ }
+ }
+
+ public static InstanceAction decomission()
+ {
+ return (target) -> {
+ target.runOnInstance(() -> {
+ try
+ {
+ StorageService.instance.decommission(false);
+ }
+ catch (InterruptedException e)
+ {
+ throw new RuntimeException();
+ }
+ });
+ };
+ }
+
+
+ public static VersionedApplicationState tokens(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.TOKENS, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).tokens(tokens));
+ }
+
+ public static VersionedApplicationState unsafeReleaseVersion(IInvokableInstance instance, String partitionerStr, String releaseVersionStr)
+ {
+ return instance.appliesOnInstance((String partitionerString, String releaseVersion) -> {
+ IPartitioner partitioner = FBUtilities.newPartitioner(partitionerString);
+ VersionedValue versionedValue = new VersionedValue.VersionedValueFactory(partitioner).releaseVersion(releaseVersion);
+ return new VersionedApplicationState(ApplicationState.RELEASE_VERSION.ordinal(), versionedValue.value, versionedValue.version);
+ }).apply(partitionerStr, releaseVersionStr);
+ }
+
+ public static VersionedApplicationState releaseVersion(IInvokableInstance instance)
+ {
+ return unsafeReleaseVersion(instance, instance.config().getString("partitioner"), instance.getReleaseVersionString());
+ }
+
+ public static VersionedApplicationState statusNormal(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens));
+ }
+
+ public static VersionedApplicationState statusWithPortNormal(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS_WITH_PORT, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens));
+ }
+
+ public static VersionedApplicationState statusBootstrapping(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).bootstrapping(tokens));
+ }
+
+ public static VersionedApplicationState statusWithPortBootstrapping(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS_WITH_PORT, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).bootstrapping(tokens));
+ }
+
+ public static VersionedApplicationState statusLeaving(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).leaving(tokens));
+ }
+
+ public static VersionedApplicationState statusWithPortLeaving(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS_WITH_PORT, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).leaving(tokens));
+ }
+
+ public static VersionedValue toVersionedValue(VersionedApplicationState vv)
+ {
+ return VersionedValue.unsafeMakeVersionedValue(vv.value, vv.version);
+ }
+
+ public static ApplicationState toApplicationState(VersionedApplicationState vv)
+ {
+ return ApplicationState.values()[vv.applicationState];
+ }
+
+ public static VersionedApplicationState unsafeVersionedToken(IInvokableInstance instance,
Review comment:
private?
##########
File path: test/distributed/org/apache/cassandra/distributed/action/GossipHelper.java
##########
@@ -0,0 +1,431 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.distributed.action;
+
+import java.io.IOException;
+import java.io.Serializable;
+import java.net.InetSocketAddress;
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.TimeUnit;
+import java.util.stream.Stream;
+
+import net.openhft.chronicle.core.util.SerializableBiFunction;
+import org.apache.cassandra.db.SystemKeyspace;
+import org.apache.cassandra.dht.IPartitioner;
+import org.apache.cassandra.dht.Token;
+import org.apache.cassandra.distributed.api.IInstance;
+import org.apache.cassandra.distributed.api.IInvokableInstance;
+import org.apache.cassandra.distributed.api.IIsolatedExecutor;
+import org.apache.cassandra.distributed.impl.Instance;
+import org.apache.cassandra.distributed.shared.VersionedApplicationState;
+import org.apache.cassandra.gms.ApplicationState;
+import org.apache.cassandra.gms.EndpointState;
+import org.apache.cassandra.gms.Gossiper;
+import org.apache.cassandra.gms.VersionedValue;
+import org.apache.cassandra.io.util.DataInputBuffer;
+import org.apache.cassandra.io.util.DataOutputBuffer;
+import org.apache.cassandra.locator.InetAddressAndPort;
+import org.apache.cassandra.locator.TokenMetadata;
+import org.apache.cassandra.net.MessagingService;
+import org.apache.cassandra.schema.MigrationManager;
+import org.apache.cassandra.service.PendingRangeCalculatorService;
+import org.apache.cassandra.service.StorageService;
+import org.apache.cassandra.utils.FBUtilities;
+
+import static org.apache.cassandra.distributed.impl.DistributedTestSnitch.toCassandraInetAddressAndPort;
+
+public class GossipHelper
+{
+ public static InstanceAction statusToBootstrap(IInvokableInstance newNode)
+ {
+ return (instance) ->
+ {
+ changeGossipState(instance,
+ newNode,
+ Arrays.asList(tokens(newNode),
+ statusBootstrapping(newNode),
+ statusWithPortBootstrapping(newNode)));
+ };
+ }
+
+ public static InstanceAction statusToNormal(IInvokableInstance peer)
+ {
+ return (target) ->
+ {
+ changeGossipState(target,
+ peer,
+ Arrays.asList(tokens(peer),
+ statusNormal(peer),
+ releaseVersion(peer),
+ statusWithPortNormal(peer)));
+ };
+ }
+
+ /**
+ * This method is unsafe and should be used _only_ when gossip is not used or available: it creates versioned values on the
+ * target instance, which means Gossip versioning gets out of sync. Use a safe couterpart at all times when performing _any_
+ * ring movement operations _or_ if Gossip is used.
+ */
+ public static InstanceAction unsafeStatusToNormal(IInstance peer)
+ {
+ return (target) ->
+ {
+ changeGossipState(target,
+ peer,
+ Arrays.asList(unsafeVersionedToken(target,
+ ApplicationState.TOKENS,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).tokens(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeVersionedToken(target,
+ ApplicationState.STATUS,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeVersionedToken(target,
+ ApplicationState.STATUS_WITH_PORT,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeReleaseVersion(target,
+ peer.config().getString("partitioner"),
+ peer.getReleaseVersionString())));
+ };
+ }
+
+ public static InstanceAction statusToLeaving(IInvokableInstance newNode)
+ {
+ return (instance) -> {
+ changeGossipState(instance,
+ newNode,
+ Arrays.asList(tokens(newNode),
+ statusLeaving(newNode),
+ statusWithPortLeaving(newNode)));
+ };
+ }
+
+ public static InstanceAction bootstrap()
+ {
+ return new BootstrapAction();
+ }
+
+ public static InstanceAction bootstrap(boolean joinRing, Duration waitForBootstrap, Duration waitForSchema)
+ {
+ return new BootstrapAction(joinRing, waitForBootstrap, waitForSchema);
+ }
+
+ public static InstanceAction disseminateGossipState(IInvokableInstance newNode)
+ {
+ return new DisseminateGossipState(newNode);
+ }
+
+ public static InstanceAction pullSchemaFrom(IInvokableInstance pullFrom)
+ {
+ return new PullSchemaFrom(pullFrom);
+ }
+
+ private static InstanceAction disableBinary()
+ {
+ return (instance) -> {
+ instance.runOnInstance(StorageService.instance::stopNativeTransport);
+ };
+ }
+
+ private static class DisseminateGossipState implements InstanceAction
+ {
+ final Map<InetSocketAddress, byte[]> gossipState;
+
+ public DisseminateGossipState(IInvokableInstance... from)
+ {
+ gossipState = new HashMap<>();
+ for (IInvokableInstance node : from)
+ {
+ byte[] epBytes = node.callsOnInstance(() -> {
+ EndpointState epState = Gossiper.instance.getEndpointStateForEndpoint(FBUtilities.getBroadcastAddressAndPort());
+ return toBytes(epState);
+ }).call();
+ gossipState.put(node.broadcastAddress(), epBytes);
+ }
+ }
+
+ public void accept(IInvokableInstance instance)
+ {
+ instance.appliesOnInstance((IIsolatedExecutor.SerializableFunction<Map<InetSocketAddress, byte[]>, Void>)
+ (map) -> {
+ Map<InetAddressAndPort, EndpointState> newState = new HashMap<>();
+ for (Map.Entry<InetSocketAddress, byte[]> e : map.entrySet())
+ newState.put(toCassandraInetAddressAndPort(e.getKey()), fromBytes(e.getValue()));
+
+ Gossiper.runInGossipStageBlocking(() -> {
+ Gossiper.instance.applyStateLocally(newState);
+ });
+ return null;
+ }).apply(gossipState);
+ }
+ }
+
+ public static byte[] toBytes(EndpointState epState)
+ {
+ try (DataOutputBuffer out = new DataOutputBuffer(1024))
+ {
+ EndpointState.serializer.serialize(epState, out, MessagingService.current_version);
+ return out.toByteArray();
+ }
+ catch (IOException e)
+ {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public static EndpointState fromBytes(byte[] bytes)
+ {
+ try (DataInputBuffer in = new DataInputBuffer(bytes))
+ {
+ return EndpointState.serializer.deserialize(in, MessagingService.current_version);
+ }
+ catch (Throwable t)
+ {
+ throw new RuntimeException(t);
+ }
+ }
+
+ private static class PullSchemaFrom implements InstanceAction
+ {
+ final InetSocketAddress pullFrom;
+
+ public PullSchemaFrom(IInvokableInstance pullFrom)
+ {
+ this.pullFrom = pullFrom.broadcastAddress();;
+ }
+
+ public void accept(IInvokableInstance pullTo)
+ {
+ pullTo.acceptsOnInstance((InetSocketAddress pullFrom) -> {
+ InetAddressAndPort endpoint = toCassandraInetAddressAndPort(pullFrom);
+ EndpointState state = Gossiper.instance.getEndpointStateForEndpoint(endpoint);
+ MigrationManager.scheduleSchemaPull(endpoint, state);
+ MigrationManager.waitUntilReadyForBootstrap();
+ }).accept(pullFrom);
+ }
+ }
+
+ private static class BootstrapAction implements InstanceAction, Serializable
+ {
+ private final boolean joinRing;
+ private final Duration waitForBootstrap;
+ private final Duration waitForSchema;
+
+ public BootstrapAction()
+ {
+ this(true, Duration.ofMinutes(10), Duration.ofSeconds(10));
+ }
+
+ public BootstrapAction(boolean joinRing, Duration waitForBootstrap, Duration waitForSchema)
+ {
+ this.joinRing = joinRing;
+ this.waitForBootstrap = waitForBootstrap;
+ this.waitForSchema = waitForSchema;
+ }
+
+ public void accept(IInvokableInstance instance)
+ {
+ instance.appliesOnInstance((String partitionerString, String tokenString) -> {
+ IPartitioner partitioner = FBUtilities.newPartitioner(partitionerString);
+ List<Token> tokens = Collections.singletonList(partitioner.getTokenFactory().fromString(tokenString));
+ try
+ {
+ SystemKeyspace.setBootstrapState(SystemKeyspace.BootstrapState.IN_PROGRESS);
+ StorageService.instance.waitForSchema((int) waitForSchema.toMillis());
+ PendingRangeCalculatorService.instance.blockUntilFinished();
+ StorageService.instance.startBootstrap(tokens).get(waitForBootstrap.toMillis(), TimeUnit.MILLISECONDS);
+ StorageService.instance.setUpDistributedSystemKeyspaces();
+ if (joinRing)
+ StorageService.instance.finishJoiningRing(true, tokens);
+ }
+ catch (Throwable t)
+ {
+ throw new RuntimeException(t);
+ }
+
+ return null;
+ }).apply(instance.config().getString("partitioner"), instance.config().getString("initial_token"));
+ }
+ }
+
+ public static InstanceAction decomission()
+ {
+ return (target) -> {
+ target.runOnInstance(() -> {
+ try
+ {
+ StorageService.instance.decommission(false);
+ }
+ catch (InterruptedException e)
+ {
+ throw new RuntimeException();
+ }
+ });
+ };
+ }
+
+
+ public static VersionedApplicationState tokens(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.TOKENS, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).tokens(tokens));
+ }
+
+ public static VersionedApplicationState unsafeReleaseVersion(IInvokableInstance instance, String partitionerStr, String releaseVersionStr)
+ {
+ return instance.appliesOnInstance((String partitionerString, String releaseVersion) -> {
+ IPartitioner partitioner = FBUtilities.newPartitioner(partitionerString);
+ VersionedValue versionedValue = new VersionedValue.VersionedValueFactory(partitioner).releaseVersion(releaseVersion);
+ return new VersionedApplicationState(ApplicationState.RELEASE_VERSION.ordinal(), versionedValue.value, versionedValue.version);
+ }).apply(partitionerStr, releaseVersionStr);
+ }
+
+ public static VersionedApplicationState releaseVersion(IInvokableInstance instance)
+ {
+ return unsafeReleaseVersion(instance, instance.config().getString("partitioner"), instance.getReleaseVersionString());
+ }
+
+ public static VersionedApplicationState statusNormal(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens));
+ }
+
+ public static VersionedApplicationState statusWithPortNormal(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS_WITH_PORT, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens));
+ }
+
+ public static VersionedApplicationState statusBootstrapping(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).bootstrapping(tokens));
+ }
+
+ public static VersionedApplicationState statusWithPortBootstrapping(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS_WITH_PORT, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).bootstrapping(tokens));
+ }
+
+ public static VersionedApplicationState statusLeaving(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).leaving(tokens));
+ }
+
+ public static VersionedApplicationState statusWithPortLeaving(IInvokableInstance instance)
+ {
+ return versionedToken(instance, ApplicationState.STATUS_WITH_PORT, (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).leaving(tokens));
+ }
+
+ public static VersionedValue toVersionedValue(VersionedApplicationState vv)
+ {
+ return VersionedValue.unsafeMakeVersionedValue(vv.value, vv.version);
+ }
+
+ public static ApplicationState toApplicationState(VersionedApplicationState vv)
Review comment:
private?
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
[GitHub] [cassandra] ifesdjeen commented on a change in pull request #759: Improve machinery for testing bootstrap and range movements
Posted by GitBox <gi...@apache.org>.
ifesdjeen commented on a change in pull request #759:
URL: https://github.com/apache/cassandra/pull/759#discussion_r504572603
##########
File path: src/java/org/apache/cassandra/gms/Gossiper.java
##########
@@ -707,6 +707,17 @@ public void unsafeAssassinateEndpoint(String address) throws UnknownHostExceptio
assassinateEndpoint(address);
}
+
+ @VisibleForTesting
+ public void unsafeAnulEndpoint(InetAddressAndPort endpoint)
Review comment:
We do this on usage.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
[GitHub] [cassandra] ifesdjeen commented on a change in pull request #759: Improve machinery for testing bootstrap and range movements
Posted by GitBox <gi...@apache.org>.
ifesdjeen commented on a change in pull request #759:
URL: https://github.com/apache/cassandra/pull/759#discussion_r504033699
##########
File path: test/distributed/org/apache/cassandra/distributed/impl/Instance.java
##########
@@ -438,24 +457,27 @@ public void startup(ICluster cluster)
// TODO: this is more than just gossip
if (config.has(GOSSIP))
{
- StorageService.instance.initServer();
+ StorageService.instance.registerDaemon(CassandraDaemon.getInstanceForTesting());
+ StorageService.instance.initServer(StorageService.RING_DELAY,
+ !startupOptions.contains(StartupOption.SKIP_RING_JOIN));
StorageService.instance.removeShutdownHook();
Gossiper.waitToSettle();
}
- else
+ else if (!startupOptions.contains(StartupOption.SKIP_RING_JOIN))
{
- initializeRing(cluster);
- }
+ cluster.stream().forEach(peer -> {
Review comment:
Sure, that makes sense. Removed conditional above.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
[GitHub] [cassandra] ifesdjeen commented on a change in pull request #759: Improve machinery for testing bootstrap and range movements
Posted by GitBox <gi...@apache.org>.
ifesdjeen commented on a change in pull request #759:
URL: https://github.com/apache/cassandra/pull/759#discussion_r508214632
##########
File path: test/distributed/org/apache/cassandra/distributed/action/GossipHelper.java
##########
@@ -0,0 +1,431 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.distributed.action;
+
+import java.io.IOException;
+import java.io.Serializable;
+import java.net.InetSocketAddress;
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.TimeUnit;
+import java.util.stream.Stream;
+
+import net.openhft.chronicle.core.util.SerializableBiFunction;
+import org.apache.cassandra.db.SystemKeyspace;
+import org.apache.cassandra.dht.IPartitioner;
+import org.apache.cassandra.dht.Token;
+import org.apache.cassandra.distributed.api.IInstance;
+import org.apache.cassandra.distributed.api.IInvokableInstance;
+import org.apache.cassandra.distributed.api.IIsolatedExecutor;
+import org.apache.cassandra.distributed.impl.Instance;
+import org.apache.cassandra.distributed.shared.VersionedApplicationState;
+import org.apache.cassandra.gms.ApplicationState;
+import org.apache.cassandra.gms.EndpointState;
+import org.apache.cassandra.gms.Gossiper;
+import org.apache.cassandra.gms.VersionedValue;
+import org.apache.cassandra.io.util.DataInputBuffer;
+import org.apache.cassandra.io.util.DataOutputBuffer;
+import org.apache.cassandra.locator.InetAddressAndPort;
+import org.apache.cassandra.locator.TokenMetadata;
+import org.apache.cassandra.net.MessagingService;
+import org.apache.cassandra.schema.MigrationManager;
+import org.apache.cassandra.service.PendingRangeCalculatorService;
+import org.apache.cassandra.service.StorageService;
+import org.apache.cassandra.utils.FBUtilities;
+
+import static org.apache.cassandra.distributed.impl.DistributedTestSnitch.toCassandraInetAddressAndPort;
+
+public class GossipHelper
+{
+ public static InstanceAction statusToBootstrap(IInvokableInstance newNode)
+ {
+ return (instance) ->
+ {
+ changeGossipState(instance,
+ newNode,
+ Arrays.asList(tokens(newNode),
+ statusBootstrapping(newNode),
+ statusWithPortBootstrapping(newNode)));
+ };
+ }
+
+ public static InstanceAction statusToNormal(IInvokableInstance peer)
+ {
+ return (target) ->
+ {
+ changeGossipState(target,
+ peer,
+ Arrays.asList(tokens(peer),
+ statusNormal(peer),
+ releaseVersion(peer),
+ statusWithPortNormal(peer)));
+ };
+ }
+
+ /**
+ * This method is unsafe and should be used _only_ when gossip is not used or available: it creates versioned values on the
+ * target instance, which means Gossip versioning gets out of sync. Use a safe couterpart at all times when performing _any_
+ * ring movement operations _or_ if Gossip is used.
+ */
+ public static InstanceAction unsafeStatusToNormal(IInstance peer)
+ {
+ return (target) ->
+ {
+ changeGossipState(target,
+ peer,
+ Arrays.asList(unsafeVersionedToken(target,
+ ApplicationState.TOKENS,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).tokens(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeVersionedToken(target,
+ ApplicationState.STATUS,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeVersionedToken(target,
+ ApplicationState.STATUS_WITH_PORT,
+ (partitioner, tokens) -> new VersionedValue.VersionedValueFactory(partitioner).normal(tokens),
+ peer.config().getString("partitioner"),
+ peer.config().getString("initial_token")),
+ unsafeReleaseVersion(target,
+ peer.config().getString("partitioner"),
+ peer.getReleaseVersionString())));
+ };
+ }
+
+ public static InstanceAction statusToLeaving(IInvokableInstance newNode)
+ {
+ return (instance) -> {
+ changeGossipState(instance,
+ newNode,
+ Arrays.asList(tokens(newNode),
+ statusLeaving(newNode),
+ statusWithPortLeaving(newNode)));
+ };
+ }
+
+ public static InstanceAction bootstrap()
+ {
+ return new BootstrapAction();
+ }
+
+ public static InstanceAction bootstrap(boolean joinRing, Duration waitForBootstrap, Duration waitForSchema)
+ {
+ return new BootstrapAction(joinRing, waitForBootstrap, waitForSchema);
+ }
+
+ public static InstanceAction disseminateGossipState(IInvokableInstance newNode)
+ {
+ return new DisseminateGossipState(newNode);
+ }
+
+ public static InstanceAction pullSchemaFrom(IInvokableInstance pullFrom)
+ {
+ return new PullSchemaFrom(pullFrom);
+ }
+
+ private static InstanceAction disableBinary()
+ {
+ return (instance) -> {
+ instance.runOnInstance(StorageService.instance::stopNativeTransport);
+ };
+ }
+
+ private static class DisseminateGossipState implements InstanceAction
+ {
+ final Map<InetSocketAddress, byte[]> gossipState;
+
+ public DisseminateGossipState(IInvokableInstance... from)
+ {
+ gossipState = new HashMap<>();
+ for (IInvokableInstance node : from)
+ {
+ byte[] epBytes = node.callsOnInstance(() -> {
+ EndpointState epState = Gossiper.instance.getEndpointStateForEndpoint(FBUtilities.getBroadcastAddressAndPort());
+ return toBytes(epState);
+ }).call();
+ gossipState.put(node.broadcastAddress(), epBytes);
+ }
+ }
+
+ public void accept(IInvokableInstance instance)
+ {
+ instance.appliesOnInstance((IIsolatedExecutor.SerializableFunction<Map<InetSocketAddress, byte[]>, Void>)
+ (map) -> {
+ Map<InetAddressAndPort, EndpointState> newState = new HashMap<>();
+ for (Map.Entry<InetSocketAddress, byte[]> e : map.entrySet())
+ newState.put(toCassandraInetAddressAndPort(e.getKey()), fromBytes(e.getValue()));
+
+ Gossiper.runInGossipStageBlocking(() -> {
+ Gossiper.instance.applyStateLocally(newState);
+ });
+ return null;
+ }).apply(gossipState);
+ }
+ }
+
+ public static byte[] toBytes(EndpointState epState)
Review comment:
Sure, switched to private.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
[GitHub] [cassandra] ifesdjeen commented on a change in pull request #759: Improve machinery for testing bootstrap and range movements
Posted by GitBox <gi...@apache.org>.
ifesdjeen commented on a change in pull request #759:
URL: https://github.com/apache/cassandra/pull/759#discussion_r504574967
##########
File path: test/distributed/org/apache/cassandra/distributed/impl/Instance.java
##########
@@ -443,25 +457,31 @@ public void startup(ICluster cluster)
StorageService.instance.registerDaemon(CassandraDaemon.getInstanceForTesting());
if (config.has(GOSSIP))
{
+ MigrationManager.setUptimeFn(() -> System.currentTimeMillis() - startedAt);
StorageService.instance.initServer();
StorageService.instance.removeShutdownHook();
Gossiper.waitToSettle();
}
else
{
- initializeRing(cluster);
- }
+ cluster.stream().forEach(peer -> {
+ // TODO: this isn't going to work for UpgradableCluster
+ GossipHelper.statusToNormal((IInvokableInstance) peer).accept(this);
+ });
- StorageService.instance.ensureTraceKeyspace();
+ }
SystemKeyspace.finishStartup();
CassandraDaemon.getInstanceForTesting().setupCompleted();
if (config.has(NATIVE_PROTOCOL))
{
+ // Start up virtual table support
+ CassandraDaemon.getInstanceForTesting().setupVirtualKeyspaces();
CassandraDaemon.getInstanceForTesting().initializeClientTransports();
CassandraDaemon.getInstanceForTesting().start();
+ StorageService.instance.setRpcReady(true);
Review comment:
Done
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
[GitHub] [cassandra] ifesdjeen commented on a change in pull request #759: Improve machinery for testing bootstrap and range movements
Posted by GitBox <gi...@apache.org>.
ifesdjeen commented on a change in pull request #759:
URL: https://github.com/apache/cassandra/pull/759#discussion_r505423638
##########
File path: test/distributed/org/apache/cassandra/distributed/test/BootstrapTest.java
##########
@@ -18,85 +18,244 @@
package org.apache.cassandra.distributed.test;
+import java.net.InetSocketAddress;
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.HashSet;
import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.locks.LockSupport;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.junit.Assert;
import org.junit.Test;
+import com.datastax.driver.core.ResultSet;
+import com.datastax.driver.core.Session;
+import com.datastax.driver.core.SimpleStatement;
+import com.datastax.driver.core.Statement;
+import com.datastax.driver.core.policies.RoundRobinPolicy;
+import org.apache.cassandra.dht.Range;
+import org.apache.cassandra.dht.Token;
import org.apache.cassandra.distributed.Cluster;
import org.apache.cassandra.distributed.api.ConsistencyLevel;
import org.apache.cassandra.distributed.api.ICluster;
import org.apache.cassandra.distributed.api.IInstanceConfig;
+import org.apache.cassandra.distributed.api.IInvokableInstance;
import org.apache.cassandra.distributed.api.TokenSupplier;
+import org.apache.cassandra.distributed.impl.DistributedTestSnitch;
+import org.apache.cassandra.distributed.impl.RowUtil;
import org.apache.cassandra.distributed.shared.NetworkTopology;
+import org.apache.cassandra.locator.EndpointsForRange;
+import org.apache.cassandra.locator.InetAddressAndPort;
+import org.apache.cassandra.service.StorageService;
+import static java.util.Arrays.*;
+import static org.apache.cassandra.distributed.action.GossipHelper.bootstrap;
+import static org.apache.cassandra.distributed.action.GossipHelper.decomission;
+import static org.apache.cassandra.distributed.action.GossipHelper.disseminateGossipState;
+import static org.apache.cassandra.distributed.action.GossipHelper.pullSchemaFrom;
+import static org.apache.cassandra.distributed.action.GossipHelper.statusToBootstrap;
import static org.apache.cassandra.distributed.api.Feature.GOSSIP;
+import static org.apache.cassandra.distributed.api.Feature.NATIVE_PROTOCOL;
import static org.apache.cassandra.distributed.api.Feature.NETWORK;
+import static org.apache.cassandra.distributed.shared.AssertUtils.assertRows;
+import static org.apache.cassandra.distributed.shared.AssertUtils.row;
-// TODO: this test should be removed after running in-jvm dtests is set up via the shared API repository
public class BootstrapTest extends TestBaseImpl
Review comment:
Broke those down
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
[GitHub] [cassandra] ifesdjeen commented on a change in pull request #759: Improve machinery for testing bootstrap and range movements
Posted by GitBox <gi...@apache.org>.
ifesdjeen commented on a change in pull request #759:
URL: https://github.com/apache/cassandra/pull/759#discussion_r507831448
##########
File path: test/distributed/org/apache/cassandra/distributed/action/GossipHelper.java
##########
@@ -0,0 +1,437 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.distributed.action;
+
+import java.io.IOException;
+import java.io.Serializable;
+import java.net.InetSocketAddress;
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.TimeUnit;
+import java.util.function.Predicate;
Review comment:
👍 fixed
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
[GitHub] [cassandra] ifesdjeen commented on a change in pull request #759: Improve machinery for testing bootstrap and range movements
Posted by GitBox <gi...@apache.org>.
ifesdjeen commented on a change in pull request #759:
URL: https://github.com/apache/cassandra/pull/759#discussion_r504570318
##########
File path: test/distributed/org/apache/cassandra/distributed/action/GossipHelper.java
##########
@@ -0,0 +1,464 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.distributed.action;
+
+
+import java.io.IOException;
+import java.net.InetSocketAddress;
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.TimeUnit;
+import java.util.function.Predicate;
+import java.util.stream.Stream;
+
+import net.openhft.chronicle.core.util.SerializableBiFunction;
+import net.openhft.chronicle.core.util.SerializableConsumer;
+import org.apache.cassandra.db.SystemKeyspace;
+import org.apache.cassandra.dht.IPartitioner;
+import org.apache.cassandra.dht.Token;
+import org.apache.cassandra.distributed.api.ICluster;
+import org.apache.cassandra.distributed.api.IInstance;
+import org.apache.cassandra.distributed.api.IInvokableInstance;
+import org.apache.cassandra.distributed.api.IIsolatedExecutor;
+import org.apache.cassandra.distributed.impl.Instance;
+import org.apache.cassandra.distributed.shared.VersionedApplicationState;
+import org.apache.cassandra.gms.ApplicationState;
+import org.apache.cassandra.gms.EndpointState;
+import org.apache.cassandra.gms.Gossiper;
+import org.apache.cassandra.gms.VersionedValue;
+import org.apache.cassandra.io.util.DataInputBuffer;
+import org.apache.cassandra.io.util.DataOutputBuffer;
+import org.apache.cassandra.locator.InetAddressAndPort;
+import org.apache.cassandra.locator.TokenMetadata;
+import org.apache.cassandra.net.MessagingService;
+import org.apache.cassandra.schema.MigrationManager;
+import org.apache.cassandra.service.PendingRangeCalculatorService;
+import org.apache.cassandra.service.StorageService;
+import org.apache.cassandra.utils.FBUtilities;
+
+import static org.apache.cassandra.distributed.impl.DistributedTestSnitch.toCassandraInetAddressAndPort;
+
+
+public class GossipHelper
+{
+
+ public static ClusterAction clusterAction(InstanceAction action)
+ {
+ return cluster -> cluster.stream().forEach(instance -> {
+ action.apply(cluster, instance);
+ });
+ }
+
+ public static ClusterAction clusterAction(InstanceAction action, Predicate<IInvokableInstance> filter)
+ {
+ return cluster -> cluster.stream().forEach(instance -> {
+ if (filter.test(instance))
+ action.apply(cluster, instance);
+ });
+ }
+
+ public static ClusterAction clusterAction(InstanceAction action, int... instanceIds)
+ {
+ return cluster -> {
+ for (int idx : instanceIds)
+ action.apply(cluster, cluster.get(idx));
+ };
+
+ }
+
+ public static InstanceAction statusToBootstrap(IInvokableInstance newNode)
+ {
+ return new StatusToBootstrap(newNode);
+ }
+
+ public static ClusterAction statusToNormal()
+ {
+ return new ClusterAction()
+ {
+ public void apply(ICluster<IInvokableInstance> cluster)
+ {
+ cluster.stream().forEach((peer) -> {
+ clusterAction(statusToNormal(peer)).apply(cluster);
+ });
+ }
+ };
+ }
+
+ public static InstanceAction statusToNormal(IInvokableInstance newNode)
+ {
+ return new StatusToBootstrap(newNode);
+ }
+
+ public static InstanceAction statusToLeaving(IInvokableInstance newNode)
+ {
+ return new StatusToLeaving(newNode);
+ }
+
+ public static InstanceAction bootstrap()
+ {
+ return new BootstrapAction();
+ }
+
+ public static InstanceAction bootstrap(boolean joinRing, Duration waitForBootstrap, Duration waitForSchema)
+ {
+ return new BootstrapAction(joinRing, waitForBootstrap, waitForSchema);
+ }
+
+ public static InstanceAction disseminateGossipState(IInvokableInstance newNode)
+ {
+ return new DisseminateGossipState(newNode);
+ }
+
+ public static InstanceAction pullSchemaFrom(IInvokableInstance pullFrom)
+ {
+ return new PullSchemaFrom(pullFrom);
+ }
+
+ private static class StatusToBootstrap implements InstanceAction
+ {
+ final IInvokableInstance newNode;
+
+ public StatusToBootstrap(IInvokableInstance newNode)
+ {
+ this.newNode = newNode;
+ }
+
+ public void apply(ICluster<IInvokableInstance> cluster, IInvokableInstance instance)
+ {
+ changeGossipState(instance,
+ newNode,
+ Arrays.asList(tokens(newNode),
+ statusBootstrapping(newNode),
+ statusWithPortBootstrapping(newNode)));
+ }
+ }
+
+ private static class StatusToLeaving implements InstanceAction
+ {
+ final IInvokableInstance newNode;
+
+ public StatusToLeaving(IInvokableInstance newNode)
+ {
+ this.newNode = newNode;
+ }
+
+ public void apply(ICluster<IInvokableInstance> cluster, IInvokableInstance instance)
+ {
+ changeGossipState(instance,
+ newNode,
+ Arrays.asList(tokens(newNode),
+ statusLeaving(newNode),
+ statusWithPortLeaving(newNode)));
+ }
+ }
+
+ private static InstanceAction disableBinary = (cluster, instance) -> {
+ instance.runOnInstance(() -> {
+ StorageService.instance.stopNativeTransport();
+ });
+ };
+
+ public static InstanceAction disableBinary()
+ {
+ return disableBinary;
+ }
+
+ private static class DisseminateGossipState implements InstanceAction
+ {
+ final IInvokableInstance[] from;
+
+ public DisseminateGossipState(IInvokableInstance... from)
+ {
+ this.from = from;
+ }
+
+ public void apply(ICluster<IInvokableInstance> cluster, IInvokableInstance instance)
+ {
+ Map<InetSocketAddress, byte[]> m = new HashMap<>();
+ for (IInvokableInstance node : from)
+ {
+ byte[] epBytes = node.callsOnInstance(() -> {
+ EndpointState epState = Gossiper.instance.getEndpointStateForEndpoint(FBUtilities.getBroadcastAddressAndPort());
+ return toBytes(epState);
+ }).call();
+ m.put(node.broadcastAddress(), epBytes);
+ }
+
+ instance.appliesOnInstance((IIsolatedExecutor.SerializableFunction<Map<InetSocketAddress, byte[]>, Void>)
+ (map) -> {
+ Map<InetAddressAndPort, EndpointState> newState = new HashMap<>();
+ for (Map.Entry<InetSocketAddress, byte[]> e : map.entrySet())
+ newState.put(toCassandraInetAddressAndPort(e.getKey()), fromBytes(e.getValue()));
+
+ Gossiper.runInGossipStageBlocking(() -> {
+ Gossiper.instance.applyStateLocally(newState);
+ });
+ return null;
+ }).apply(m);
+ }
+ }
+
+ public static byte[] toBytes(EndpointState epState)
+ {
+ try (DataOutputBuffer out = new DataOutputBuffer(1024))
+ {
+ EndpointState.serializer.serialize(epState, out, MessagingService.current_version);
+ return out.toByteArray();
+ }
+ catch (IOException e)
+ {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public static EndpointState fromBytes(byte[] bytes)
+ {
+ try (DataInputBuffer in = new DataInputBuffer(bytes))
+ {
+ return EndpointState.serializer.deserialize(in, MessagingService.current_version);
+ }
+ catch (Throwable t)
+ {
+ throw new RuntimeException(t);
+ }
+ }
+
+ private static class PullSchemaFrom implements InstanceAction
+ {
+ final IInvokableInstance pullFrom;
+
+ public PullSchemaFrom(IInvokableInstance pullFrom)
+ {
+ this.pullFrom = pullFrom;
+ }
+
+ public void apply(ICluster<IInvokableInstance> cluster, IInvokableInstance pullTo)
Review comment:
> But they don't currently
They don't. It was a forward-looking statement.
> why not just use functions?
You're suggesting to use static methods, not functions. I've explained motivation behind implementing an interface rather than functions above (uniformity, reusability, etc).
> interfaces harder to understand as I need to figure out what they do, but relying on simple functions removes the ambiguity.
This is simply not true. Both for a method call and an interface implementation you have to jump to definition to see what's really going on.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
[GitHub] [cassandra] ifesdjeen commented on a change in pull request #759: Improve machinery for testing bootstrap and range movements
Posted by GitBox <gi...@apache.org>.
ifesdjeen commented on a change in pull request #759:
URL: https://github.com/apache/cassandra/pull/759#discussion_r504036643
##########
File path: test/distributed/org/apache/cassandra/distributed/action/GossipHelper.java
##########
@@ -0,0 +1,464 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.distributed.action;
+
+
+import java.io.IOException;
+import java.net.InetSocketAddress;
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.TimeUnit;
+import java.util.function.Predicate;
+import java.util.stream.Stream;
+
+import net.openhft.chronicle.core.util.SerializableBiFunction;
+import net.openhft.chronicle.core.util.SerializableConsumer;
+import org.apache.cassandra.db.SystemKeyspace;
+import org.apache.cassandra.dht.IPartitioner;
+import org.apache.cassandra.dht.Token;
+import org.apache.cassandra.distributed.api.ICluster;
+import org.apache.cassandra.distributed.api.IInstance;
+import org.apache.cassandra.distributed.api.IInvokableInstance;
+import org.apache.cassandra.distributed.api.IIsolatedExecutor;
+import org.apache.cassandra.distributed.impl.Instance;
+import org.apache.cassandra.distributed.shared.VersionedApplicationState;
+import org.apache.cassandra.gms.ApplicationState;
+import org.apache.cassandra.gms.EndpointState;
+import org.apache.cassandra.gms.Gossiper;
+import org.apache.cassandra.gms.VersionedValue;
+import org.apache.cassandra.io.util.DataInputBuffer;
+import org.apache.cassandra.io.util.DataOutputBuffer;
+import org.apache.cassandra.locator.InetAddressAndPort;
+import org.apache.cassandra.locator.TokenMetadata;
+import org.apache.cassandra.net.MessagingService;
+import org.apache.cassandra.schema.MigrationManager;
+import org.apache.cassandra.service.PendingRangeCalculatorService;
+import org.apache.cassandra.service.StorageService;
+import org.apache.cassandra.utils.FBUtilities;
+
+import static org.apache.cassandra.distributed.impl.DistributedTestSnitch.toCassandraInetAddressAndPort;
+
+
+public class GossipHelper
+{
+
+ public static ClusterAction clusterAction(InstanceAction action)
+ {
+ return cluster -> cluster.stream().forEach(instance -> {
+ action.apply(cluster, instance);
+ });
+ }
+
+ public static ClusterAction clusterAction(InstanceAction action, Predicate<IInvokableInstance> filter)
+ {
+ return cluster -> cluster.stream().forEach(instance -> {
+ if (filter.test(instance))
+ action.apply(cluster, instance);
+ });
+ }
+
+ public static ClusterAction clusterAction(InstanceAction action, int... instanceIds)
+ {
+ return cluster -> {
+ for (int idx : instanceIds)
+ action.apply(cluster, cluster.get(idx));
+ };
+
+ }
+
+ public static InstanceAction statusToBootstrap(IInvokableInstance newNode)
+ {
+ return new StatusToBootstrap(newNode);
+ }
+
+ public static ClusterAction statusToNormal()
+ {
+ return new ClusterAction()
+ {
+ public void apply(ICluster<IInvokableInstance> cluster)
+ {
+ cluster.stream().forEach((peer) -> {
+ clusterAction(statusToNormal(peer)).apply(cluster);
+ });
+ }
+ };
+ }
+
+ public static InstanceAction statusToNormal(IInvokableInstance newNode)
+ {
+ return new StatusToBootstrap(newNode);
+ }
+
+ public static InstanceAction statusToLeaving(IInvokableInstance newNode)
+ {
+ return new StatusToLeaving(newNode);
+ }
+
+ public static InstanceAction bootstrap()
+ {
+ return new BootstrapAction();
+ }
+
+ public static InstanceAction bootstrap(boolean joinRing, Duration waitForBootstrap, Duration waitForSchema)
+ {
+ return new BootstrapAction(joinRing, waitForBootstrap, waitForSchema);
+ }
+
+ public static InstanceAction disseminateGossipState(IInvokableInstance newNode)
+ {
+ return new DisseminateGossipState(newNode);
+ }
+
+ public static InstanceAction pullSchemaFrom(IInvokableInstance pullFrom)
+ {
+ return new PullSchemaFrom(pullFrom);
+ }
+
+ private static class StatusToBootstrap implements InstanceAction
+ {
+ final IInvokableInstance newNode;
+
+ public StatusToBootstrap(IInvokableInstance newNode)
+ {
+ this.newNode = newNode;
+ }
+
+ public void apply(ICluster<IInvokableInstance> cluster, IInvokableInstance instance)
+ {
+ changeGossipState(instance,
+ newNode,
+ Arrays.asList(tokens(newNode),
+ statusBootstrapping(newNode),
+ statusWithPortBootstrapping(newNode)));
+ }
+ }
+
+ private static class StatusToLeaving implements InstanceAction
+ {
+ final IInvokableInstance newNode;
+
+ public StatusToLeaving(IInvokableInstance newNode)
+ {
+ this.newNode = newNode;
+ }
+
+ public void apply(ICluster<IInvokableInstance> cluster, IInvokableInstance instance)
+ {
+ changeGossipState(instance,
+ newNode,
+ Arrays.asList(tokens(newNode),
+ statusLeaving(newNode),
+ statusWithPortLeaving(newNode)));
+ }
+ }
+
+ private static InstanceAction disableBinary = (cluster, instance) -> {
+ instance.runOnInstance(() -> {
+ StorageService.instance.stopNativeTransport();
+ });
+ };
+
+ public static InstanceAction disableBinary()
+ {
+ return disableBinary;
+ }
+
+ private static class DisseminateGossipState implements InstanceAction
+ {
+ final IInvokableInstance[] from;
+
+ public DisseminateGossipState(IInvokableInstance... from)
+ {
+ this.from = from;
+ }
+
+ public void apply(ICluster<IInvokableInstance> cluster, IInvokableInstance instance)
+ {
+ Map<InetSocketAddress, byte[]> m = new HashMap<>();
+ for (IInvokableInstance node : from)
+ {
+ byte[] epBytes = node.callsOnInstance(() -> {
+ EndpointState epState = Gossiper.instance.getEndpointStateForEndpoint(FBUtilities.getBroadcastAddressAndPort());
+ return toBytes(epState);
+ }).call();
+ m.put(node.broadcastAddress(), epBytes);
+ }
+
+ instance.appliesOnInstance((IIsolatedExecutor.SerializableFunction<Map<InetSocketAddress, byte[]>, Void>)
+ (map) -> {
+ Map<InetAddressAndPort, EndpointState> newState = new HashMap<>();
+ for (Map.Entry<InetSocketAddress, byte[]> e : map.entrySet())
+ newState.put(toCassandraInetAddressAndPort(e.getKey()), fromBytes(e.getValue()));
+
+ Gossiper.runInGossipStageBlocking(() -> {
+ Gossiper.instance.applyStateLocally(newState);
+ });
+ return null;
+ }).apply(m);
+ }
+ }
+
+ public static byte[] toBytes(EndpointState epState)
+ {
+ try (DataOutputBuffer out = new DataOutputBuffer(1024))
+ {
+ EndpointState.serializer.serialize(epState, out, MessagingService.current_version);
+ return out.toByteArray();
+ }
+ catch (IOException e)
+ {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public static EndpointState fromBytes(byte[] bytes)
+ {
+ try (DataInputBuffer in = new DataInputBuffer(bytes))
+ {
+ return EndpointState.serializer.deserialize(in, MessagingService.current_version);
+ }
+ catch (Throwable t)
+ {
+ throw new RuntimeException(t);
+ }
+ }
+
+ private static class PullSchemaFrom implements InstanceAction
+ {
+ final IInvokableInstance pullFrom;
+
+ public PullSchemaFrom(IInvokableInstance pullFrom)
+ {
+ this.pullFrom = pullFrom;
+ }
+
+ public void apply(ICluster<IInvokableInstance> cluster, IInvokableInstance pullTo)
Review comment:
The idea behind "actions" was in making such things work for multi-version clusters. We could make them named and each version could apply its corresponding version. But other than that - these actions _are_ in fact just functions.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
[GitHub] [cassandra] ifesdjeen commented on a change in pull request #759: Improve machinery for testing bootstrap and range movements
Posted by GitBox <gi...@apache.org>.
ifesdjeen commented on a change in pull request #759:
URL: https://github.com/apache/cassandra/pull/759#discussion_r508287464
##########
File path: test/distributed/org/apache/cassandra/distributed/impl/Instance.java
##########
@@ -519,72 +524,6 @@ private Config loadConfig(IInstanceConfig overrides)
return config;
}
- private void initializeRing(ICluster cluster)
- {
- // This should be done outside instance in order to avoid serializing config
- String partitionerName = config.getString("partitioner");
- List<String> initialTokens = new ArrayList<>();
- List<InetSocketAddress> hosts = new ArrayList<>();
- List<UUID> hostIds = new ArrayList<>();
- List<String> versions = new ArrayList<>();
- for (int i = 1 ; i <= cluster.size() ; ++i)
- {
- IInstance instance = cluster.get(i);
- IInstanceConfig config = instance.config();
- initialTokens.add(config.getString("initial_token"));
- hosts.add(config.broadcastAddress());
- hostIds.add(config.hostId());
- versions.add(instance.getReleaseVersionString());
- }
-
- try
- {
- IPartitioner partitioner = FBUtilities.newPartitioner(partitionerName);
- StorageService storageService = StorageService.instance;
- List<Token> tokens = new ArrayList<>();
- for (String token : initialTokens)
- tokens.add(partitioner.getTokenFactory().fromString(token));
-
- for (int i = 0; i < tokens.size(); i++)
- {
- InetSocketAddress ep = hosts.get(i);
- InetAddressAndPort addressAndPort = toCassandraInetAddressAndPort(ep);
- UUID hostId = hostIds.get(i);
- Token token = tokens.get(i);
- String releaseVersion = versions.get(i);
- Gossiper.runInGossipStageBlocking(() -> {
- Gossiper.instance.initializeNodeUnsafe(addressAndPort, hostId, 1);
- Gossiper.instance.injectApplicationState(addressAndPort,
- ApplicationState.TOKENS,
- new VersionedValue.VersionedValueFactory(partitioner).tokens(Collections.singleton(token)));
- Gossiper.instance.injectApplicationState(addressAndPort,
- ApplicationState.RELEASE_VERSION,
- new VersionedValue.VersionedValueFactory(partitioner).releaseVersion(releaseVersion));
- storageService.onChange(addressAndPort,
- ApplicationState.STATUS_WITH_PORT,
- new VersionedValue.VersionedValueFactory(partitioner).normal(Collections.singleton(token)));
- storageService.onChange(addressAndPort,
- ApplicationState.STATUS,
- new VersionedValue.VersionedValueFactory(partitioner).normal(Collections.singleton(token)));
- Gossiper.instance.realMarkAlive(addressAndPort, Gossiper.instance.getEndpointStateForEndpoint(addressAndPort));
- });
-
- int messagingVersion = cluster.get(ep).isShutdown()
Review comment:
I've added net_version. Thanks!
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
[GitHub] [cassandra] ifesdjeen commented on a change in pull request #759: Improve machinery for testing bootstrap and range movements
Posted by GitBox <gi...@apache.org>.
ifesdjeen commented on a change in pull request #759:
URL: https://github.com/apache/cassandra/pull/759#discussion_r507829779
##########
File path: src/java/org/apache/cassandra/gms/VersionedValue.java
##########
@@ -27,6 +27,7 @@
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.Iterables;
+import com.fasterxml.jackson.core.Versioned;
Review comment:
Sure! Fixed now.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
[GitHub] [cassandra] dcapwell commented on a change in pull request #759: Improve machinery for testing bootstrap and range movements
Posted by GitBox <gi...@apache.org>.
dcapwell commented on a change in pull request #759:
URL: https://github.com/apache/cassandra/pull/759#discussion_r504116148
##########
File path: src/java/org/apache/cassandra/net/MessagingService.java
##########
@@ -431,6 +431,12 @@ public void shutdown()
public void shutdown(long timeout, TimeUnit units, boolean shutdownGracefully, boolean shutdownExecutors)
{
+ if (isShuttingDown)
Review comment:
I am ok with this, just curious why it was added. I added logic to ignore the error thrown during jvm-dtest shutdown
```
(IgnoreThrowingRunnable) () -> MessagingService.instance().shutdown(1L, MINUTES, false, true)
```
so only curious what triggered this change?
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
[GitHub] [cassandra] ifesdjeen commented on a change in pull request #759: Improve machinery for testing bootstrap and range movements
Posted by GitBox <gi...@apache.org>.
ifesdjeen commented on a change in pull request #759:
URL: https://github.com/apache/cassandra/pull/759#discussion_r504574028
##########
File path: test/distributed/org/apache/cassandra/distributed/impl/Instance.java
##########
@@ -443,25 +457,31 @@ public void startup(ICluster cluster)
StorageService.instance.registerDaemon(CassandraDaemon.getInstanceForTesting());
if (config.has(GOSSIP))
{
+ MigrationManager.setUptimeFn(() -> System.currentTimeMillis() - startedAt);
StorageService.instance.initServer();
StorageService.instance.removeShutdownHook();
Gossiper.waitToSettle();
}
else
{
- initializeRing(cluster);
- }
+ cluster.stream().forEach(peer -> {
+ // TODO: this isn't going to work for UpgradableCluster
+ GossipHelper.statusToNormal((IInvokableInstance) peer).accept(this);
+ });
- StorageService.instance.ensureTraceKeyspace();
+ }
SystemKeyspace.finishStartup();
CassandraDaemon.getInstanceForTesting().setupCompleted();
if (config.has(NATIVE_PROTOCOL))
{
+ // Start up virtual table support
+ CassandraDaemon.getInstanceForTesting().setupVirtualKeyspaces();
Review comment:
This wasn't there at the time of writing; removed in favour of the other one
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
[GitHub] [cassandra] ifesdjeen commented on a change in pull request #759: Improve machinery for testing bootstrap and range movements
Posted by GitBox <gi...@apache.org>.
ifesdjeen commented on a change in pull request #759:
URL: https://github.com/apache/cassandra/pull/759#discussion_r504033473
##########
File path: test/distributed/org/apache/cassandra/distributed/impl/Instance.java
##########
@@ -438,24 +457,27 @@ public void startup(ICluster cluster)
// TODO: this is more than just gossip
if (config.has(GOSSIP))
{
- StorageService.instance.initServer();
+ StorageService.instance.registerDaemon(CassandraDaemon.getInstanceForTesting());
Review comment:
Fixed
##########
File path: test/distributed/org/apache/cassandra/distributed/impl/Instance.java
##########
@@ -438,24 +457,27 @@ public void startup(ICluster cluster)
// TODO: this is more than just gossip
if (config.has(GOSSIP))
{
- StorageService.instance.initServer();
+ StorageService.instance.registerDaemon(CassandraDaemon.getInstanceForTesting());
+ StorageService.instance.initServer(StorageService.RING_DELAY,
+ !startupOptions.contains(StartupOption.SKIP_RING_JOIN));
Review comment:
Fixed
##########
File path: test/distributed/org/apache/cassandra/distributed/impl/Instance.java
##########
@@ -438,24 +457,27 @@ public void startup(ICluster cluster)
// TODO: this is more than just gossip
if (config.has(GOSSIP))
{
- StorageService.instance.initServer();
+ StorageService.instance.registerDaemon(CassandraDaemon.getInstanceForTesting());
+ StorageService.instance.initServer(StorageService.RING_DELAY,
+ !startupOptions.contains(StartupOption.SKIP_RING_JOIN));
StorageService.instance.removeShutdownHook();
Gossiper.waitToSettle();
}
- else
+ else if (!startupOptions.contains(StartupOption.SKIP_RING_JOIN))
{
- initializeRing(cluster);
- }
+ cluster.stream().forEach(peer -> {
Review comment:
Fixed
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org