maedhroz commented on a change in pull request #1301:
URL: https://github.com/apache/cassandra/pull/1301#discussion_r797065695



##########
File path: 
test/distributed/org/apache/cassandra/distributed/test/streaming/StreamCloseInMiddleTest.java
##########
@@ -0,0 +1,204 @@
+/*
+ * 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.test.streaming;
+
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.util.Arrays;
+import java.util.List;
+import java.util.concurrent.Callable;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import java.util.stream.Collectors;
+
+import org.junit.Test;
+
+import net.bytebuddy.ByteBuddy;
+import net.bytebuddy.dynamic.loading.ClassLoadingStrategy;
+import net.bytebuddy.implementation.MethodDelegation;
+import net.bytebuddy.implementation.bind.annotation.SuperCall;
+import org.apache.cassandra.db.rows.UnfilteredRowIterator;
+import org.apache.cassandra.db.streaming.CassandraIncomingFile;
+import org.apache.cassandra.distributed.Cluster;
+import org.apache.cassandra.distributed.api.Feature;
+import org.apache.cassandra.distributed.api.IInvokableInstance;
+import org.apache.cassandra.distributed.api.LogResult;
+import org.apache.cassandra.distributed.api.TokenSupplier;
+import org.apache.cassandra.distributed.shared.ClusterUtils;
+import org.apache.cassandra.distributed.test.TestBaseImpl;
+import org.apache.cassandra.io.sstable.format.RangeAwareSSTableWriter;
+import org.apache.cassandra.io.sstable.format.big.BigTableZeroCopyWriter;
+import org.apache.cassandra.io.util.SequentialWriter;
+import org.assertj.core.api.Assertions;
+
+import static net.bytebuddy.matcher.ElementMatchers.named;
+import static net.bytebuddy.matcher.ElementMatchers.takesArguments;
+
+public class StreamCloseInMiddleTest extends TestBaseImpl
+{
+    @Test
+    public void zeroCopy() throws IOException
+    {
+        streamClose(true);
+    }
+
+    @Test
+    public void notZeroCopy() throws IOException
+    {
+        streamClose(false);
+    }
+
+    private void streamClose(boolean zeroCopyStreaming) throws IOException
+    {
+        try (Cluster cluster = Cluster.build(2)
+                                      
.withTokenSupplier(TokenSupplier.evenlyDistributedTokens(3))
+                                      
.withInstanceInitializer(BBHelper::install)
+                                      .withConfig(c -> c.with(Feature.values())
+                                                        
.set("stream_entire_sstables", zeroCopyStreaming)
+                                                        // when die, this will 
try to halt JVM, which is easier to validate in the test
+                                                        // other levels 
require checking state of the subsystems
+                                                        
.set("disk_failure_policy", "die"))
+                                      .start())
+        {
+            init(cluster);
+
+            cluster.schemaChange(withKeyspace("CREATE TABLE %s.tbl (pk int 
PRIMARY KEY)"));
+
+            triggerStreaming(cluster, zeroCopyStreaming);
+            // make sure disk failure policy is not triggered
+            assertNoNodeShutdown(cluster);
+
+            // now bootstrap a new node; streaming will fail
+            IInvokableInstance node3 = ClusterUtils.addInstance(cluster, c -> 
c.set("auto_bootstrap", true));
+            node3.startup();
+            for (String line : Arrays.asList("Error while waiting on bootstrap 
to complete. Bootstrap will have to be restarted", // bootstrap failed
+                                             "Some data streaming failed. Use 
nodetool to check bootstrap state and resume")) // didn't join ring because 
bootstrap failed
+                Assertions.assertThat(node3.logs().grep(line).getResult())
+                          .hasSize(1);
+
+            assertNoNodeShutdown(cluster);
+        }
+    }
+
+    private void assertNoNodeShutdown(Cluster cluster)
+    {
+        AssertionError t = null;
+        for (IInvokableInstance i : 
cluster.stream().collect(Collectors.toList()))
+        {
+            try
+            {
+                Assertions.assertThat(i.isShutdown()).describedAs("%s was 
shutdown; this is not expected", i).isFalse();
+                Assertions.assertThat(i.killAttempts()).describedAs("%s saw 
kill attempts; this is not expected", i).isEqualTo(0);
+            }
+            catch (AssertionError t2)
+            {
+                if (t == null)
+                    t = t2;
+                else
+                    t.addSuppressed(t2);
+            }
+        }
+        if (t != null)
+            throw t;
+    }
+
+    private static void triggerStreaming(Cluster cluster, boolean 
expectedEntireSSTable)
+    {
+        // preemptive log search to make sure classes load... seems there is a 
bug where a downed instance can't return access to logs
+        cluster.forEach(n -> n.logs().grep("testing"));
+
+        IInvokableInstance node1 = cluster.get(1);
+        IInvokableInstance node2 = cluster.get(2);
+
+        // repair will do streaming IFF there is a mismatch; so cause one
+        for (int i = 0; i < 10; i++)
+            node1.executeInternal(withKeyspace("INSERT INTO %s.tbl (pk) VALUES 
(?)"), i);
+
+        // we do not have metrics for streaming impl; this is only done in 
debug level logging... so enable debug logging if not on
+        cluster.forEach(n -> n.nodetoolResult("setlogginglevel", "streaming", 
"DEBUG").asserts().success());
+
+        // trigger streaming; expected to fail as streaming socket closed in 
the middle (currently this is an unrecoverable event)
+        long mark = node2.logs().mark();
+        node2.nodetoolResult("repair", "-full", KEYSPACE, 
"tbl").asserts().failure();
+
+        assertStreamingFailed(node2, expectedEntireSSTable, mark);
+    }
+
+    private static void assertStreamingFailed(IInvokableInstance node, boolean 
expectedEntireSSTable, long mark)
+    {
+        // make sure zero-copy streaming was done; only way to know is by 
checking debug logs on the receiving end
+        LogResult<List<String>> logs = node.logs().grep(mark, "Incoming stream 
entireSSTable=");
+        Assertions.assertThat(logs.getResult()).isNotEmpty();
+        Pattern pattern = Pattern.compile("entireSSTable=(.*?)\\s");
+        logs.getResult().forEach(line -> {
+            Matcher match = pattern.matcher(logs.getResult().get(0));
+            Assertions.assertThat(match.find()).isTrue();
+            boolean entireSSTable = Boolean.parseBoolean(match.group(1));
+            
Assertions.assertThat(entireSSTable).isEqualTo(expectedEntireSSTable);
+        });
+    }
+
+    public static class BBHelper
+    {
+        @SuppressWarnings("unused")
+        public static int writeDirectlyToChannel(ByteBuffer buf, @SuperCall 
Callable<Integer> zuper) throws Exception
+        {
+            if (isCaller(BigTableZeroCopyWriter.class.getName(), "write"))
+                throw new java.nio.channels.ClosedChannelException();
+            // different context; pass through
+            return zuper.call();
+        }
+
+        @SuppressWarnings("unused")
+        public static boolean append(UnfilteredRowIterator partition, 
@SuperCall Callable<Boolean> zuper) throws Exception
+        {
+            if (isCaller(CassandraIncomingFile.class.getName(), "read")) // 
handles compressed and non-compressed
+                throw new java.nio.channels.ClosedChannelException();
+            // different context; pass through
+            return zuper.call();
+        }
+
+        private static boolean isCaller(String klass, String method)
+        {
+            //TODO is there a cleaner way to check this?

Review comment:
       I think there's `StackWalker` in Java 9, but that's no help to us :)




-- 
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: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]



---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to