You are viewing a plain text version of this content. The canonical link for it is here.
Posted to pr@cassandra.apache.org by "frankgh (via GitHub)" <gi...@apache.org> on 2023/05/09 19:51:06 UTC
[GitHub] [cassandra-sidecar] frankgh opened a new pull request, #45: CEP-28: Implement Bulk API endpoints and introduce the Sidecar Client to Support Bulk Analytics
frankgh opened a new pull request, #45:
URL: https://github.com/apache/cassandra-sidecar/pull/45
This PR implements the remaining endpoints needed to perform Bulk Analytics operations that allow
reading and writing data from Cassandra in Bulk. The new endpoints include:
- Endpoint to create snapshots
- Endpoint to clear a snapshot
- Endpoint to upload SSTable components
- Endpoint to clean up uploads for SSTable components
- Endpoint to import SSTable components
- Endpoint to retrieve gossip info
- Endpoint to retrieve the time skew for the server
- Endpoint to retrieve the ring information
Sidecar Client
Introduces the fully featured sidecar client to access Cassandra Sidecar endpoints.
It offers support for retries and Sidecar instance selection policies. The client
project itself is technology-agnostic, but we provide a vertx implementation for
the `HttpClient`. The Sidecar vertx-client can be published as a shaded-jar to be
consumed by clients where the dependencies can cause issues, especially in environments
where the dependencies are not always controlled by the consumers (for example Spark).
Co-authored-by: Saranya Krishnakumar <sa...@apple.com>
Co-authored-by: Yifan Cai <yc...@apache.org>
Co-authored-by: Francisco Guerrero <fr...@gmail.com>
Co-authored-by: Doug Rohrer <dr...@apple.com>
--
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-sidecar] frankgh commented on a diff in pull request #45: CEP-28: Implement Bulk API endpoints and introduce the Sidecar Client to Support Bulk Analytics
Posted by "frankgh (via GitHub)" <gi...@apache.org>.
frankgh commented on code in PR #45:
URL: https://github.com/apache/cassandra-sidecar/pull/45#discussion_r1192872710
##########
client/src/main/java/org/apache/cassandra/sidecar/client/selection/OrderedInstanceSelectionPolicy.java:
##########
@@ -0,0 +1,54 @@
+/*
+ * 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.sidecar.client.selection;
+
+import java.util.Iterator;
+
+import org.apache.cassandra.sidecar.client.SidecarInstance;
+import org.apache.cassandra.sidecar.client.SidecarInstancesProvider;
+import org.jetbrains.annotations.NotNull;
+
+/**
+ * A selection policy for a multiple Cassandra Sidecar instances where the iterator returns in order
+ */
+public class OrderedInstanceSelectionPolicy implements InstanceSelectionPolicy
+{
+ protected final SidecarInstancesProvider instancesProvider;
+
+ /**
+ * Constructs a new {@link OrderedInstanceSelectionPolicy} with the provided list of instances
+ *
+ * @param instancesProvider the class that provides the sidecar instances
+ */
+ public OrderedInstanceSelectionPolicy(SidecarInstancesProvider instancesProvider)
+ {
+ this.instancesProvider = instancesProvider;
+ }
+
+ /**
+ * Returns an iterator of {@link SidecarInstance instances}.
+ *
+ * @return an iterator of {@link SidecarInstance instances}
+ */
+ @NotNull
+ public Iterator<SidecarInstance> iterator()
+ {
+ return instancesProvider.instances().iterator();
Review Comment:
good point. I guess this really means that we won't randomly sort the instances provided
--
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-sidecar] frankgh commented on a diff in pull request #45: CEP-28: Implement Bulk API endpoints and introduce the Sidecar Client to Support Bulk Analytics
Posted by "frankgh (via GitHub)" <gi...@apache.org>.
frankgh commented on code in PR #45:
URL: https://github.com/apache/cassandra-sidecar/pull/45#discussion_r1194430129
##########
vertx-client-shaded/build.gradle:
##########
@@ -0,0 +1,123 @@
+/*
+ * 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.
+ */
+
+/**
+ * The sole purpose of this sub-project is to produce a shaded package for the vertx-client. Currently,
+ * the shadow plugin has some limitations when producing a non-shaded and shaded versions of the jar.
+ */
+
+import com.github.jengelman.gradle.plugins.shadow.transformers.CacheableTransformer
+import com.github.jengelman.gradle.plugins.shadow.transformers.Transformer
+import com.github.jengelman.gradle.plugins.shadow.transformers.TransformerContext
+import shadow.org.apache.tools.zip.ZipEntry
+import shadow.org.apache.tools.zip.ZipOutputStream
+
+plugins {
+ id('java-library')
+ id('maven-publish')
+ id('com.github.johnrengelman.shadow') version '6.1.0'
+}
+
+group 'org.apache.cassandra.sidecar'
+version project.version
+
+sourceCompatibility = 1.8
+
+configurations {
+ all*.exclude(group: 'ch.qos.logback')
+}
+
+dependencies {
+ shadow(group: 'org.slf4j', name: 'slf4j-api', version: "${project.slf4jVersion}")
+ shadow(group: 'com.fasterxml.jackson.core', name: 'jackson-annotations', version: '2.14.2')
+ api(project(':vertx-client'))
+}
+
+// Relocating a Package
+shadowJar {
+ archiveClassifier.set('')
+ relocate 'com.fasterxml.jackson.core', 'o.a.c.sidecar.client.shaded.com.fasterxml.jackson.core'
+ relocate 'com.fasterxml.jackson.databind', 'o.a.c.sidecar.client.shaded.com.fasterxml.jackson.databind'
+ relocate 'io.netty', 'o.a.c.sidecar.client.shaded.io.netty'
+ relocate 'io.vertx', 'o.a.c.sidecar.client.shaded.io.vertx'
+ relocate 'META-INF/native/libnetty', 'META-INF/native/sidecar_client_netty_shaded_netty'
+ relocate 'META-INF/native/netty', 'META-INF/native/io_sidecar_client_netty_shaded_netty'
+ relocate 'META-INF/versions/11/io/vertx', 'META-INF/versions/11/o/a/c/sidecar/client/shaded/io/vertx'
+ transform(NettyResourceTransformer.class)
+ mergeServiceFiles()
+
+ dependencies {
+ exclude(dependency('org.slf4j:.*:.*'))
+ // Exclude the jackson-annotations dependency so that extension clients can keep annotating POJOs
+ // without the need to use shadow annotations. For example, they can continue using
+ // com.fasterxml.jackson.annotation.JsonProperty.
+ exclude(dependency('com.fasterxml.jackson.core:jackson-annotations:.*'))
+ }
+}
+
+publishing {
+ publications {
+ shadow(MavenPublication) { publication ->
+ project.shadow.component(publication)
+
+ groupId project.group
+ artifactId "vertx-client-all"
+ version System.getenv("CODE_VERSION") ?: "${version}"
+ }
+ }
+}
+
+/**
+ * A Transformer which updates the Netty JAR META-INF/ resources to accurately
+ * reference shaded class names.
+ */
+@CacheableTransformer
+class NettyResourceTransformer implements Transformer {
Review Comment:
this is just renaming netty directories in the fat jar :)
--
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-sidecar] yifan-c commented on a diff in pull request #45: CEP-28: Implement Bulk API endpoints and introduce the Sidecar Client to Support Bulk Analytics
Posted by "yifan-c (via GitHub)" <gi...@apache.org>.
yifan-c commented on code in PR #45:
URL: https://github.com/apache/cassandra-sidecar/pull/45#discussion_r1194355882
##########
common/src/test/java/org/apache/cassandra/sidecar/common/SimpleCassandraVersionProviderTest.java:
##########
@@ -78,7 +78,7 @@ void ensureOutOfOrderInsertionWorks()
.add(new V41())
.add(new V30()).build();
- ICassandraFactory cassandra = provider.getCassandra(SimpleCassandraVersion.create("4.0.0"));
+ ICassandraFactory cassandra = provider.cassandra(SimpleCassandraVersion.create("4.0.0"));
assertThat(cassandra).hasSameClassAs(new V40());
Review Comment:
~To test `ensureOutOfOrderInsertionWorks`, should it get V30 from version `SimpleCassandraVersion.create("3.0.0")`?~
~After I made the change, it actually fails, meaning the insertion order has to be in the ascending order of the versions. Either updating the test case or the implementation of builder is needed.~
It is unrelated with this patch, please ignore.
--
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-sidecar] frankgh commented on a diff in pull request #45: CEP-28: Implement Bulk API endpoints and introduce the Sidecar Client to Support Bulk Analytics
Posted by "frankgh (via GitHub)" <gi...@apache.org>.
frankgh commented on code in PR #45:
URL: https://github.com/apache/cassandra-sidecar/pull/45#discussion_r1194429307
##########
src/main/java/org/apache/cassandra/sidecar/utils/RequestUtils.java:
##########
@@ -18,30 +18,29 @@
package org.apache.cassandra.sidecar.utils;
+import io.vertx.core.http.HttpServerRequest;
+
/**
* Utility class for Http request related operations.
*/
public class RequestUtils
{
/**
- * Given a combined host address like 127.0.0.1:9042 or [2001:db8:0:0:0:ff00:42:8329]:9042, this method
- * removes port information and returns 127.0.0.1 or 2001:db8:0:0:0:ff00:42:8329.
- * @param address
- * @return host address without port information
+ * Parses a boolean parameter from the {@code request}, for the given {@code headerName}. If the request param
+ * is not {@code true} or {@code false}, it returns the {@code defaultValue}.
+ *
+ * @param request the request
+ * @param headerName the name of the header
+ * @param defaultValue the default value when the request parameter does not match {@code true} or {@code false}
+ * @return the parsed value for the {@code headerName} from the {@code request}
*/
- public static String extractHostAddressWithoutPort(String address)
+ public static boolean parseBooleanHeader(HttpServerRequest request, String headerName, boolean defaultValue)
{
- if (address.contains(":"))
- {
- // just ipv6 host name present without port information
- if (address.split(":").length > 2 && !address.startsWith("["))
- {
- return address;
- }
- String host = address.substring(0, address.lastIndexOf(':'));
- // remove brackets from ipv6 addresses
- return host.startsWith("[") ? host.substring(1, host.length() - 1) : host;
- }
- return address;
+ String value = request.getParam(headerName);
+ if ("true".equalsIgnoreCase(value))
+ return true;
+ if ("false".equalsIgnoreCase(value))
+ return false;
+ return defaultValue;
Review Comment:
it's not quite the same. This method takes only true or false, case insensitively. parseBoolean compares to true only.
--
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-sidecar] yifan-c commented on a diff in pull request #45: CEP-28: Implement Bulk API endpoints and introduce the Sidecar Client to Support Bulk Analytics
Posted by "yifan-c (via GitHub)" <gi...@apache.org>.
yifan-c commented on code in PR #45:
URL: https://github.com/apache/cassandra-sidecar/pull/45#discussion_r1194539547
##########
src/main/java/org/apache/cassandra/sidecar/utils/RequestUtils.java:
##########
@@ -18,30 +18,29 @@
package org.apache.cassandra.sidecar.utils;
+import io.vertx.core.http.HttpServerRequest;
+
/**
* Utility class for Http request related operations.
*/
public class RequestUtils
{
/**
- * Given a combined host address like 127.0.0.1:9042 or [2001:db8:0:0:0:ff00:42:8329]:9042, this method
- * removes port information and returns 127.0.0.1 or 2001:db8:0:0:0:ff00:42:8329.
- * @param address
- * @return host address without port information
+ * Parses a boolean parameter from the {@code request}, for the given {@code headerName}. If the request param
+ * is not {@code true} or {@code false}, it returns the {@code defaultValue}.
+ *
+ * @param request the request
+ * @param headerName the name of the header
+ * @param defaultValue the default value when the request parameter does not match {@code true} or {@code false}
+ * @return the parsed value for the {@code headerName} from the {@code request}
*/
- public static String extractHostAddressWithoutPort(String address)
+ public static boolean parseBooleanHeader(HttpServerRequest request, String headerName, boolean defaultValue)
{
- if (address.contains(":"))
- {
- // just ipv6 host name present without port information
- if (address.split(":").length > 2 && !address.startsWith("["))
- {
- return address;
- }
- String host = address.substring(0, address.lastIndexOf(':'));
- // remove brackets from ipv6 addresses
- return host.startsWith("[") ? host.substring(1, host.length() - 1) : host;
- }
- return address;
+ String value = request.getParam(headerName);
+ if ("true".equalsIgnoreCase(value))
+ return true;
+ if ("false".equalsIgnoreCase(value))
+ return false;
+ return defaultValue;
Review Comment:
I thought it is equivalent to
```java
return Boolean.parseBoolean(request.getParam(headerName, String.valueOf(defaultValue)));
```
--
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-sidecar] yifan-c commented on a diff in pull request #45: CEP-28: Implement Bulk API endpoints and introduce the Sidecar Client to Support Bulk Analytics
Posted by "yifan-c (via GitHub)" <gi...@apache.org>.
yifan-c commented on code in PR #45:
URL: https://github.com/apache/cassandra-sidecar/pull/45#discussion_r1194138051
##########
client/src/main/java/org/apache/cassandra/sidecar/client/selection/OrderedInstanceSelectionPolicy.java:
##########
@@ -0,0 +1,54 @@
+/*
+ * 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.sidecar.client.selection;
+
+import java.util.Iterator;
+
+import org.apache.cassandra.sidecar.client.SidecarInstance;
+import org.apache.cassandra.sidecar.client.SidecarInstancesProvider;
+import org.jetbrains.annotations.NotNull;
+
+/**
+ * A selection policy for a multiple Cassandra Sidecar instances where the iterator returns in order
+ */
+public class OrderedInstanceSelectionPolicy implements InstanceSelectionPolicy
+{
+ protected final SidecarInstancesProvider instancesProvider;
+
+ /**
+ * Constructs a new {@link OrderedInstanceSelectionPolicy} with the provided list of instances
+ *
+ * @param instancesProvider the class that provides the sidecar instances
+ */
+ public OrderedInstanceSelectionPolicy(SidecarInstancesProvider instancesProvider)
+ {
+ this.instancesProvider = instancesProvider;
+ }
+
+ /**
+ * Returns an iterator of {@link SidecarInstance instances}.
+ *
+ * @return an iterator of {@link SidecarInstance instances}
+ */
+ @NotNull
+ public Iterator<SidecarInstance> iterator()
+ {
+ return instancesProvider.instances().iterator();
Review Comment:
It is fine to leave it as-is. The original comment is a nit.
--
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-sidecar] yifan-c commented on a diff in pull request #45: CEP-28: Implement Bulk API endpoints and introduce the Sidecar Client to Support Bulk Analytics
Posted by "yifan-c (via GitHub)" <gi...@apache.org>.
yifan-c commented on code in PR #45:
URL: https://github.com/apache/cassandra-sidecar/pull/45#discussion_r1195483083
##########
cassandra40/src/main/java/org/apache/cassandra/sidecar/cassandra40/TokenRangeReplicas.java:
##########
@@ -0,0 +1,515 @@
+/*
+ * 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.sidecar.cassandra40;
+
+import java.math.BigInteger;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Set;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import com.google.common.base.Objects;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.VisibleForTesting;
+
+
+/**
+ * Representation of a token range and the corresponding mapping to replica-set hosts. The range corresponds to
+ * an exclusive start range and inclusive end range {@code (start, end]}.
+ */
+public class TokenRangeReplicas implements Comparable<TokenRangeReplicas>
+{
+ private final BigInteger start;
+ private final BigInteger end;
+
+ private final Partitioner partitioner;
+
+ private final Set<String> replicaSet;
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(TokenRangeReplicas.class);
+
+ public TokenRangeReplicas(BigInteger start, BigInteger end, Partitioner partitioner, Set<String> replicaSet)
+ {
+ this.start = start;
+ this.end = end;
+ this.partitioner = partitioner;
+ this.replicaSet = replicaSet;
+ }
+
+
+ public BigInteger start()
+ {
+ return start;
+ }
+
+ public BigInteger end()
+ {
+ return end;
+ }
+
+ public Set<String> replicaSet()
+ {
+ return replicaSet;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public int compareTo(@NotNull TokenRangeReplicas other)
+ {
+ validateMatchingPartitioner(other);
+
+ BigInteger maxValue = this.partitioner.maxToken;
+ if (this.start.compareTo(other.start) == 0)
+ {
+ if (this.end.equals(maxValue)) return 1;
+ else if (other.end.equals(maxValue)) return -1;
+ else return this.end.compareTo(other.end);
+ }
+ else return this.start.compareTo(other.start);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public boolean equals(Object o)
+ {
+ if (!(o instanceof TokenRangeReplicas))
+ {
+ return false;
+ }
+ TokenRangeReplicas that = (TokenRangeReplicas) o;
+ return (this.start.equals(that.start) && this.end.equals(that.end) && this.partitioner == that.partitioner);
Review Comment:
Use `Objects.equals` instead..
--
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-sidecar] frankgh commented on a diff in pull request #45: CEP-28: Implement Bulk API endpoints and introduce the Sidecar Client to Support Bulk Analytics
Posted by "frankgh (via GitHub)" <gi...@apache.org>.
frankgh commented on code in PR #45:
URL: https://github.com/apache/cassandra-sidecar/pull/45#discussion_r1191774402
##########
src/test/java/org/apache/cassandra/sidecar/routes/sstableuploads/BaseUploadsHandlerTest.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.sidecar.routes.sstableuploads;
+
+import java.io.File;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.UUID;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.stream.Stream;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.io.TempDir;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.datastax.driver.core.KeyspaceMetadata;
+import com.datastax.driver.core.Metadata;
+import com.datastax.driver.core.TableMetadata;
+import com.google.inject.AbstractModule;
+import com.google.inject.Guice;
+import com.google.inject.Injector;
+import com.google.inject.Provides;
+import com.google.inject.Singleton;
+import com.google.inject.util.Modules;
+import io.vertx.core.Vertx;
+import io.vertx.core.http.HttpServer;
+import io.vertx.ext.web.client.WebClient;
+import io.vertx.junit5.VertxTestContext;
+import org.apache.cassandra.sidecar.Configuration;
+import org.apache.cassandra.sidecar.MainModule;
+import org.apache.cassandra.sidecar.TestModule;
+import org.apache.cassandra.sidecar.cluster.InstancesConfig;
+import org.apache.cassandra.sidecar.common.CassandraAdapterDelegate;
+import org.apache.cassandra.sidecar.config.CacheConfiguration;
+import org.apache.cassandra.sidecar.config.WorkerPoolConfiguration;
+import org.apache.cassandra.sidecar.snapshots.SnapshotUtils;
+
+import static org.apache.cassandra.sidecar.snapshots.SnapshotUtils.mockInstancesConfig;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+/**
+ * Common functionality for the SSTable Uploads {@link SSTableUploadHandler}, {@link SSTableImportHandler},
+ * and {@link SSTableCleanupHandler} tests.
+ */
+class BaseUploadsHandlerTest
+{
+ protected final Logger logger = LoggerFactory.getLogger(this.getClass());
Review Comment:
yeah, classes that extend this base class can use the logger.
--
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-sidecar] frankgh commented on a diff in pull request #45: CEP-28: Implement Bulk API endpoints and introduce the Sidecar Client to Support Bulk Analytics
Posted by "frankgh (via GitHub)" <gi...@apache.org>.
frankgh commented on code in PR #45:
URL: https://github.com/apache/cassandra-sidecar/pull/45#discussion_r1194411106
##########
cassandra40/src/main/java/org/apache/cassandra/sidecar/cassandra40/TokenRangeReplicas.java:
##########
@@ -0,0 +1,415 @@
+/*
+ * 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.sidecar.cassandra40;
+
+import java.math.BigInteger;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Set;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import com.google.common.base.Objects;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.jetbrains.annotations.NotNull;
+
+
+/**
+ * Representation of a token range and the corresponding mapping to replica-set hosts
+ */
+public class TokenRangeReplicas implements Comparable<TokenRangeReplicas>
+{
+ private final BigInteger start;
+ private final BigInteger end;
+
+ private final Partitioner partitioner;
+
+ private final Set<String> replicaSet;
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(TokenRangeReplicas.class);
+
+ public TokenRangeReplicas(BigInteger start, BigInteger end, Partitioner partitioner, Set<String> replicaSet)
+ {
+ this.start = start;
+ this.end = end;
+ this.partitioner = partitioner;
+ this.replicaSet = replicaSet;
+ }
+
+
+ public BigInteger start()
+ {
+ return start;
+ }
+
+ public BigInteger end()
+ {
+ return end;
+ }
+
+ public Set<String> replicaSet()
+ {
+ return replicaSet;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public int compareTo(@NotNull TokenRangeReplicas other)
+ {
+ if (this.partitioner != other.partitioner)
+ throw new IllegalStateException("Token ranges being compared do not have the same partitioner");
+
+ BigInteger maxValue = this.partitioner.maxToken;
+ if (this.start.compareTo(other.start) == 0)
+ {
+ if (this.end.equals(maxValue)) return 1;
+ else if (other.end.equals(maxValue)) return -1;
+ else return this.end.compareTo(other.end);
+ }
+ else return this.start.compareTo(other.start);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public boolean equals(Object o)
+ {
+ if (!(o instanceof TokenRangeReplicas))
+ {
+ return false;
+ }
+ TokenRangeReplicas that = (TokenRangeReplicas) o;
+ return (this.start.equals(that.start) && this.end.equals(that.end) && this.partitioner == that.partitioner);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public int hashCode()
+ {
+ return Objects.hashCode(start, end, partitioner);
+ }
+
+ private boolean isWrapAround()
+ {
+ return start.compareTo(end) >= 0;
+ }
+
+ private boolean isSubsetOf(TokenRangeReplicas other)
+ {
+ if (this.partitioner != other.partitioner)
+ throw new IllegalStateException("Token ranges being compared do not have the same partitioner");
+
+ BigInteger maxValue = this.partitioner.maxToken;
+ if (this.start.compareTo(other.start) >= 0)
+ {
+ if (other.end.equals(maxValue)) return true;
+ if (this.end.equals(maxValue)) return false;
+ if (this.end.compareTo(other.end) <= 0) return true;
+ }
+ return false;
+ }
+
+ /**
+ * For subset ranges, this is used to determine if a range is larger than the other by comparing start-end lengths
+ * If both ranges end at the min, we compare starting points to determine the result.
+ * When the left range is the only one ending at min, it is always the larger one since all subsequent ranges
+ * in the sorted range list have to be smaller.
+ *
+ * @param other the next range in the range list to compare
+ * @return true if "this" range is larger than the other
+ */
+ private boolean isLarger(TokenRangeReplicas other)
Review Comment:
Added some unit tests. I also added javadocs clarifying that this method assumes that the ranges are normalized and unwrapped, i.e. `this` comes before `other` AND there's no wrapping around the min token
--
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-sidecar] frankgh commented on a diff in pull request #45: CEP-28: Implement Bulk API endpoints and introduce the Sidecar Client to Support Bulk Analytics
Posted by "frankgh (via GitHub)" <gi...@apache.org>.
frankgh commented on code in PR #45:
URL: https://github.com/apache/cassandra-sidecar/pull/45#discussion_r1194431152
##########
src/main/java/org/apache/cassandra/sidecar/data/SchemaRequest.java:
##########
@@ -15,24 +15,34 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.cassandra.sidecar.common.data;
+package org.apache.cassandra.sidecar.data;
import org.jetbrains.annotations.Nullable;
/**
* Holder class for the {@link org.apache.cassandra.sidecar.routes.SchemaHandler}
* request parameters
*/
-public class SchemaRequest extends QualifiedTableName
+public class SchemaRequest
Review Comment:
this is not really the payload, these are path params.
--
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-sidecar] yifan-c commented on a diff in pull request #45: CEP-28: Implement Bulk API endpoints and introduce the Sidecar Client to Support Bulk Analytics
Posted by "yifan-c (via GitHub)" <gi...@apache.org>.
yifan-c commented on code in PR #45:
URL: https://github.com/apache/cassandra-sidecar/pull/45#discussion_r1191781069
##########
cassandra40/build.gradle:
##########
@@ -12,7 +13,34 @@ repositories {
mavenCentral()
}
+test {
+ useJUnitPlatform()
+}
+
dependencies {
- compile project(":common")
- implementation('org.jetbrains:annotations:23.0.0')
+ implementation(project(":common"))
+ compileOnly('org.jetbrains:annotations:23.0.0')
+ compileOnly('com.datastax.cassandra:cassandra-driver-core:3.11.3')
+ implementation("com.google.guava:guava:${project.rootProject.guavaVersion}")
+ implementation("org.slf4j:slf4j-api:${project.slf4jVersion}")
+
+ testImplementation "org.junit.jupiter:junit-jupiter-api:${project.junitVersion}"
+ testImplementation "org.junit.jupiter:junit-jupiter-params:${project.junitVersion}"
+ testImplementation "org.assertj:assertj-core:3.24.2"
+ testRuntimeOnly "org.junit.jupiter:junit-jupiter-engine:${project.junitVersion}"
+
+ testImplementation('org.mockito:mockito-core:4.10.0')
+ testImplementation('org.mockito:mockito-inline:4.10.0')
+
+}
+
+publishing {
Review Comment:
nit: maybe declare it in the `allprojects` block of the root project.
##########
cassandra40/src/main/java/org/apache/cassandra/sidecar/cassandra40/TokenRangeReplicas.java:
##########
@@ -0,0 +1,417 @@
+/*
+ * 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.sidecar.cassandra40;
+
+import java.math.BigInteger;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Set;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import com.google.common.base.Objects;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.jetbrains.annotations.NotNull;
+
+
+/**
+ * Representation of a token range and the corresponding mapping to replica-set hosts
+ */
+public class TokenRangeReplicas implements Comparable<TokenRangeReplicas>
+{
+ private final BigInteger start;
+ private final BigInteger end;
+
+ private final Partitioner partitioner;
+
+ private final Set<String> replicaSet;
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(TokenRangeReplicas.class);
+
+ public TokenRangeReplicas(BigInteger start, BigInteger end, Partitioner partitioner, Set<String> replicaSet)
+ {
+ this.start = start;
+ this.end = end;
+ this.partitioner = partitioner;
+ this.replicaSet = replicaSet;
+ }
+
+
+ public BigInteger start()
+ {
+ return start;
+ }
+
+ public BigInteger end()
+ {
+ return end;
+ }
+
+ public Set<String> replicaSet()
+ {
+ return replicaSet;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public int compareTo(@NotNull TokenRangeReplicas other)
+ {
+ if (this.partitioner != other.partitioner)
+ throw new IllegalStateException("Token ranges being compared do not have the same partitioner");
+
+ // TODO
+ BigInteger maxValue = this.partitioner.maxToken;
+ if (this.start.compareTo(other.start) == 0)
+ {
+ if (this.end.equals(maxValue)) return 1;
+ else if (other.end.equals(maxValue)) return -1;
+ else return this.end.compareTo(other.end);
+ }
+ else return this.start.compareTo(other.start);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public boolean equals(Object o)
+ {
+ if (!(o instanceof TokenRangeReplicas))
+ {
+ return false;
+ }
+ TokenRangeReplicas that = (TokenRangeReplicas) o;
+ return (this.start.equals(that.start) && this.end.equals(that.end) && this.partitioner == that.partitioner);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public int hashCode()
+ {
+ return Objects.hashCode(start, end, partitioner);
+ }
+
+ private boolean isWrapAround()
+ {
+ return start.compareTo(end) >= 0;
+ }
+
+ private boolean isSubsetOf(TokenRangeReplicas other)
+ {
+ if (this.partitioner != other.partitioner)
+ throw new IllegalStateException("Token ranges being compared do not have the same partitioner");
+
+ BigInteger maxValue = this.partitioner.maxToken;
+ if (this.start.compareTo(other.start) >= 0)
+ {
+ // TODO:
+ if (other.end.equals(maxValue)) return true;
+ if (this.end.equals(maxValue)) return false;
+ if (this.end.compareTo(other.end) <= 0) return true;
+ }
+ return false;
+ }
+
+ /**
+ * For subset ranges, this is used to determine if a range is larger than the other by comparing start-end lengths
+ * If both ranges end at the min, we compare starting points to determine the result.
+ * When the left range is the only one ending at min, it is always the larger one since all subsequent ranges
+ * in the sorted range list have to be smaller.
+ *
+ * @param other the next range in the range list to compare
+ * @return true if "this" range is larger than the other
+ */
+ private boolean isLarger(TokenRangeReplicas other)
+ {
+ if (this.partitioner != other.partitioner)
+ throw new IllegalStateException("Token ranges being compared do not have the same partitioner");
+
+ // If both ranges end at min, we compare start of ranges
+ if (this.end.equals(partitioner.maxToken) && other.end.equals(partitioner.maxToken))
+ {
+ return this.start.compareTo(other.start) < 0;
+ }
+
+ if (this.end.equals(partitioner.maxToken)) return true;
+ if (other.end.equals(partitioner.maxToken)) return false;
+
+ return this.end.subtract(this.start).compareTo(other.end.subtract(other.start)) > 0;
+ }
+
+ /**
+ * Determines intersection if the next range starts before the current range ends.
+ * When the current range ending at min, we determine intersection merely if the next range starts after the current
+ * since all subsequent ranges have to be subsets.
+ *
+ * @param other the range we are currently processing to check if "this" intersects it
+ * @return true if "this" range intersects the other
+ */
+ private boolean intersects(TokenRangeReplicas other)
+ {
+ return (other.end.compareTo(partitioner.maxToken) == 0 && this.start.compareTo(other.start) > 0) ||
+ this.start.compareTo(other.end) < 0;
+ }
Review Comment:
I think this implementation is wrong. You want to compare `this.end.compareTo(other.start) < 0;`. Before the comparison, it needs to sort the 2 ranges by `start`, and make sure to compare left range with right range.
Beside that, the first condition that checks with the maxToken of the partitioner seems not necessary. It only wants to compare 2 ranges.
The below test fails
```java
@Test
void testInterests()
{
TokenRangeReplicas range1 = new TokenRangeReplicas(BigInteger.valueOf(1), BigInteger.valueOf(10), Partitioner.Murmur3, new HashSet<>());
TokenRangeReplicas range2 = new TokenRangeReplicas(BigInteger.valueOf(9), BigInteger.valueOf(12), Partitioner.Murmur3, new HashSet<>());
assertThat(range1.intersects(range2)).isTrue();
assertThat(range2.intersects(range1)).isTrue();
TokenRangeReplicas range3 = new TokenRangeReplicas(BigInteger.valueOf(1), BigInteger.valueOf(10), Partitioner.Murmur3, new HashSet<>());
TokenRangeReplicas range4 = new TokenRangeReplicas(BigInteger.valueOf(11), BigInteger.valueOf(20), Partitioner.Murmur3, new HashSet<>());
assertThat(range3.intersects(range4)).isFalse();
assertThat(range4.intersects(range3)).isFalse();
}
```
##########
cassandra40/src/main/java/org/apache/cassandra/sidecar/cassandra40/RingProvider.java:
##########
@@ -0,0 +1,211 @@
+/*
+ * 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.sidecar.cassandra40;
+
+import java.net.UnknownHostException;
+import java.text.DecimalFormat;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import com.google.common.net.HostAndPort;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.apache.cassandra.sidecar.common.JmxClient;
+import org.apache.cassandra.sidecar.common.data.RingEntry;
+import org.apache.cassandra.sidecar.common.data.RingResponse;
+import org.apache.cassandra.sidecar.common.dns.DnsResolver;
+import org.jetbrains.annotations.Nullable;
+
+import static org.apache.cassandra.sidecar.cassandra40.EndpointSnitchJmxOperations.ENDPOINT_SNITCH_INFO_OBJ_NAME;
+import static org.apache.cassandra.sidecar.cassandra40.StorageJmxOperations.STORAGE_SERVICE_OBJ_NAME;
+
+/**
+ * Aggregates the ring view of cluster
+ */
+public class RingProvider
+{
+ private static final Logger LOGGER = LoggerFactory.getLogger(RingProvider.class);
+ private static final String UNKNOWN_SHORT = "?";
+ private static final String UNKNOWN = "Unknown";
+ private static final String STATUS_UP = "Up";
+ private static final String STATUS_DOWN = "Down";
+ private static final String STATE_JOINING = "Joining";
+ private static final String STATE_LEAVING = "Leaving";
+ private static final String STATE_MOVING = "Moving";
+ private static final String STATE_NORMAL = "Normal";
+ private static final String DECIMAL_FORMAT = "##0.00%";
+
+ private final JmxClient jmxClient;
+ private final DnsResolver dnsResolver;
+
+ public RingProvider(JmxClient jmxClient, DnsResolver dnsResolver)
+ {
+ this.jmxClient = jmxClient;
+ this.dnsResolver = dnsResolver;
+ }
+
+ @SuppressWarnings("UnstableApiUsage")
+ public RingResponse ring(@Nullable String keyspace) throws UnknownHostException
+ {
+ StorageJmxOperations probe = jmxClient.proxy(StorageJmxOperations.class, STORAGE_SERVICE_OBJ_NAME);
+ EndpointSnitchJmxOperations epSnitchInfo = jmxClient.proxy(EndpointSnitchJmxOperations.class,
+ ENDPOINT_SNITCH_INFO_OBJ_NAME);
+
+ // Collect required data from the probe
+ List<String> liveNodes = probe.getLiveNodesWithPort();
+ List<String> deadNodes = probe.getUnreachableNodesWithPort();
+ Status status = new Status(liveNodes, deadNodes);
+ List<String> joiningNodes = probe.getJoiningNodesWithPort();
+ List<String> leavingNodes = probe.getLeavingNodesWithPort();
+ List<String> movingNodes = probe.getMovingNodesWithPort();
+ State state = new State(joiningNodes, leavingNodes, movingNodes);
+ Map<String, String> loadMap = probe.getLoadMapWithPort();
+ Map<String, String> tokensToEndpoints = probe.getTokenToEndpointWithPortMap();
+ Map<String, String> endpointsToHostIds = probe.getEndpointWithPortToHostId();
+
+ boolean showEffectiveOwnership = true;
+ // Calculate per-token ownership of the ring
+ Map<String, Float> ownerships;
+ try
+ {
+ ownerships = probe.effectiveOwnershipWithPort(keyspace);
+ }
+ catch (IllegalStateException ex)
+ {
+ ownerships = probe.getOwnershipWithPort();
+ LOGGER.warn("Unable to retrieve effective ownership information for keyspace={}", keyspace, ex);
+ showEffectiveOwnership = false;
+ }
+
+ // DecimalFormat is not thread-safe, so we need to create a new instance per thread
+ DecimalFormat ownsFormat = new DecimalFormat(DECIMAL_FORMAT);
+ RingResponse response = new RingResponse(tokensToEndpoints.size());
+ for (Map.Entry<String, String> entry : tokensToEndpoints.entrySet())
+ {
+ String endpoint = entry.getValue();
+ String token = entry.getKey();
+ HostAndPort hap = resolve(endpoint, dnsResolver);
+ Float owns = ownerships.get(endpoint);
+ RingEntry ringEntry = new RingEntry.Builder()
+ .datacenter(epSnitchInfo.getDatacenter(endpoint))
+ .rack(queryRack(epSnitchInfo, endpoint))
+ .status(status.of(endpoint))
+ .state(state.of(endpoint))
+ .load(loadMap.getOrDefault(endpoint, UNKNOWN_SHORT))
+ .owns(formatOwns(showEffectiveOwnership, ownsFormat, owns))
+ .token(token)
+ .address(hap.getHost())
+ .port(hap.getPort())
+ .fqdn(dnsResolver.reverseResolve(hap.getHost()))
+ .hostId(endpointsToHostIds.getOrDefault(endpoint, UNKNOWN))
+ .build();
+ response.add(ringEntry);
+ }
+
+ return response;
+ }
+
+ /**
+ * Resolves the endpoint to the format "IP_ADDRESS:PORT"
+ *
+ * @return host and port. Port defaults to -1 if not included in endpoint.
+ * @throws UnknownHostException when endpoint cannot be resolved
+ */
+ @SuppressWarnings("UnstableApiUsage")
+ private static HostAndPort resolve(String endpoint, DnsResolver resolver) throws UnknownHostException
+ {
+ HostAndPort hap = HostAndPort.fromString(endpoint);
+ String address = resolver.resolve(hap.getHost());
+ return HostAndPort.fromParts(address, hap.getPortOrDefault(-1));
+ }
+
+ private static String formatOwns(boolean showEffectiveOwnership, DecimalFormat ownsFormat, Float owns)
+ {
+ if (showEffectiveOwnership && owns != null)
+ return ownsFormat.format(owns);
+ return UNKNOWN_SHORT;
+ }
+
+ /**
+ * Data class to get status of endppints
Review Comment:
nit
```suggestion
* Data class to get status of endpoints
```
##########
cassandra40/src/main/java/org/apache/cassandra/sidecar/cassandra40/StorageJmxOperations.java:
##########
@@ -1,12 +1,103 @@
+/*
+ * 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.sidecar.cassandra40;
+import java.util.List;
import java.util.Map;
/**
- * An interface that pulls a method from the Cassandra Storage Service Proxy
+ * An interface that pulls methods from the Cassandra Storage Service Proxy
*/
public interface StorageJmxOperations
{
+ String STORAGE_SERVICE_OBJ_NAME = "org.apache.cassandra.db:type=StorageService";
+
+ /**
+ * Retrieve the list of live nodes in the cluster, where "liveness" is
+ * determined by the failure detector of the node being queried.
+ *
+ * @return set of IP addresses, as Strings
+ */
+ List<String> getLiveNodesWithPort();
+
+ /**
+ * Retrieve the list of unreachable nodes in the cluster, as determined
+ * by this node's failure detector.
+ *
+ * @return set of IP addresses, as Strings
+ */
+ List<String> getUnreachableNodesWithPort();
+
+ /**
+ * Retrieve the list of nodes currently bootstrapping into the ring.
+ *
+ * @return set of IP addresses, as Strings
+ */
+ List<String> getJoiningNodesWithPort();
+
+ /**
+ * Retrieve the list of nodes currently leaving the ring.
+ *
+ * @return set of IP addresses, as Strings
+ */
+ List<String> getLeavingNodesWithPort();
+
+ /**
+ * Retrieve the list of nodes currently moving in the ring.
+ *
+ * @return set of IP addresses, as Strings
+ */
+ List<String> getMovingNodesWithPort();
+
+ /**
+ * Human-readable load value. Keys are IP addresses.
+ */
+ Map<String, String> getLoadMapWithPort();
+
+ /**
+ * Retrieve a map of tokens to endpoints, including the bootstrapping
+ * ones.
+ *
+ * @return a map of tokens to endpoints in ascending order
+ */
+ Map<String, String> getTokenToEndpointWithPortMap();
+
+ /**
+ * Effective ownership is % of the data each node owns given the keyspace
+ * we calculate the percentage using replication factor.
+ * If Keyspace == null, this method will try to verify if all the keyspaces
+ * in the cluster have the same replication strategies and if yes then we will
+ * use the first else a empty Map is returned.
Review Comment:
nit
```suggestion
* use the first else an empty Map is returned.
```
--
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-sidecar] frankgh commented on a diff in pull request #45: CEP-28: Implement Bulk API endpoints and introduce the Sidecar Client to Support Bulk Analytics
Posted by "frankgh (via GitHub)" <gi...@apache.org>.
frankgh commented on code in PR #45:
URL: https://github.com/apache/cassandra-sidecar/pull/45#discussion_r1194426923
##########
src/main/java/org/apache/cassandra/sidecar/routes/sstableuploads/SSTableCleanupHandler.java:
##########
@@ -0,0 +1,110 @@
+/*
+ * 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.sidecar.routes.sstableuploads;
+
+import java.nio.file.NoSuchFileException;
+
+import com.google.inject.Inject;
+import io.netty.handler.codec.http.HttpResponseStatus;
+import io.vertx.core.http.HttpMethod;
+import io.vertx.core.http.HttpServerRequest;
+import io.vertx.core.net.SocketAddress;
+import io.vertx.ext.web.RoutingContext;
+import org.apache.cassandra.sidecar.concurrent.ExecutorPools;
+import org.apache.cassandra.sidecar.routes.AbstractHandler;
+import org.apache.cassandra.sidecar.utils.InstanceMetadataFetcher;
+import org.apache.cassandra.sidecar.utils.SSTableUploadsPathBuilder;
+
+import static org.apache.cassandra.sidecar.utils.HttpExceptions.wrapHttpException;
+
+/**
+ * Manages cleaning up uploaded SSTables
+ */
+public class SSTableCleanupHandler extends AbstractHandler<String>
+{
+ private static final String UPLOAD_ID_PARAM = "uploadId";
+ private final SSTableUploadsPathBuilder uploadPathBuilder;
+
+ /**
+ * Constructs a handler with the provided {@code metadataFetcher}
+ *
+ * @param metadataFetcher the instance metadata fetcher
+ * @param uploadPathBuilder a class that provides SSTableUploads directories
+ * @param executorPools executor pools for blocking executions
+ */
+ @Inject
+ protected SSTableCleanupHandler(InstanceMetadataFetcher metadataFetcher,
+ SSTableUploadsPathBuilder uploadPathBuilder,
+ ExecutorPools executorPools)
+ {
+ super(metadataFetcher, executorPools, null);
+ this.uploadPathBuilder = uploadPathBuilder;
+ }
+
+ /**
+ * Handles cleaning up the SSTable upload staging directory
+ *
+ * @param context the context for the handler
+ */
+ @Override
+ public void handleInternal(RoutingContext context,
+ HttpServerRequest httpRequest,
+ String host,
+ SocketAddress remoteAddress,
+ String uploadId)
+ {
+ if (context.request().method() != HttpMethod.DELETE)
+ {
+ context.fail(wrapHttpException(HttpResponseStatus.BAD_REQUEST, "Unknown API requested"));
+ return;
+ }
Review Comment:
oh interesting. that should not be there.
--
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-sidecar] frankgh commented on a diff in pull request #45: CEP-28: Implement Bulk API endpoints and introduce the Sidecar Client to Support Bulk Analytics
Posted by "frankgh (via GitHub)" <gi...@apache.org>.
frankgh commented on code in PR #45:
URL: https://github.com/apache/cassandra-sidecar/pull/45#discussion_r1194071412
##########
client/src/main/java/org/apache/cassandra/sidecar/client/exception/UnexpectedStatusCodeException.java:
##########
@@ -0,0 +1,53 @@
+/*
+ * 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.sidecar.client.exception;
+
+/**
+ * Represents an exception raised when an unexpected status code is encountered
+ */
+public class UnexpectedStatusCodeException extends RuntimeException
+{
+ /**
+ * Constructs a new {@link UnexpectedStatusCodeException} with the given {@code statusCode} and {@code body}
+ *
+ * @param statusCode the response status code
+ * @param body the body of the response
+ */
+ public UnexpectedStatusCodeException(int statusCode, String body)
Review Comment:
good point. I think this can be a binary file that we stream
--
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-sidecar] frankgh commented on pull request #45: CEP-28: Implement Bulk API endpoints and introduce the Sidecar Client to Support Bulk Analytics
Posted by "frankgh (via GitHub)" <gi...@apache.org>.
frankgh commented on PR #45:
URL: https://github.com/apache/cassandra-sidecar/pull/45#issuecomment-1546063415
@dineshjoshi thanks for the review. I've applied your patch and addressed your comments. Let me know if there is any additional feedback
--
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-sidecar] frankgh commented on a diff in pull request #45: CEP-28: Implement Bulk API endpoints and introduce the Sidecar Client to Support Bulk Analytics
Posted by "frankgh (via GitHub)" <gi...@apache.org>.
frankgh commented on code in PR #45:
URL: https://github.com/apache/cassandra-sidecar/pull/45#discussion_r1194292976
##########
client/src/test/java/org/apache/cassandra/sidecar/client/selection/SingleInstanceSelectionPolicyTest.java:
##########
@@ -0,0 +1,56 @@
+/*
+ * 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.sidecar.client.selection;
+
+import java.util.Iterator;
+import java.util.NoSuchElementException;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import org.apache.cassandra.sidecar.client.SidecarInstance;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
+import static org.mockito.Mockito.mock;
+
+class SingleInstanceSelectionPolicyTest
+{
+ SidecarInstance mockSidecarInstance;
+
+ @BeforeEach
+ void setup()
+ {
+ mockSidecarInstance = mock(SidecarInstance.class);
+ }
+
+ @Test
+ void testIterator()
+ {
+ InstanceSelectionPolicy instanceSelectionPolicy = new SingleInstanceSelectionPolicy(mockSidecarInstance);
+ Iterator<SidecarInstance> iterator = instanceSelectionPolicy.iterator();
+
+ assertThat(iterator.hasNext()).isTrue();
+ assertThat(iterator.hasNext()).isTrue().as("Expected to be true");
Review Comment:
I'm testing idempotency of hasNext here, so I will add a comment to make it clear
--
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-sidecar] frankgh commented on a diff in pull request #45: CEP-28: Implement Bulk API endpoints and introduce the Sidecar Client to Support Bulk Analytics
Posted by "frankgh (via GitHub)" <gi...@apache.org>.
frankgh commented on code in PR #45:
URL: https://github.com/apache/cassandra-sidecar/pull/45#discussion_r1194337403
##########
client/src/test/java/org/apache/cassandra/sidecar/client/retry/ExponentialBackoffRetryPolicyTest.java:
##########
@@ -0,0 +1,139 @@
+/*
+ * 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.sidecar.client.retry;
+
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CompletionException;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.atomic.AtomicLong;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+
+import org.apache.cassandra.sidecar.client.HttpResponse;
+import org.apache.cassandra.sidecar.client.exception.RetriesExhaustedException;
+import org.apache.cassandra.sidecar.client.request.Request;
+
+import static io.netty.handler.codec.http.HttpResponseStatus.INTERNAL_SERVER_ERROR;
+import static io.netty.handler.codec.http.HttpResponseStatus.OK;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
+import static org.assertj.core.api.Fail.fail;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+class ExponentialBackoffRetryPolicyTest
+{
+ Request mockRequest;
+ HttpResponse mockResponse;
+
+ @BeforeEach
+ public void setup()
+ {
+ mockRequest = mock(Request.class);
+ mockResponse = mock(HttpResponse.class);
+ when(mockRequest.requestURI()).thenReturn("/api/uri");
+ }
+
+ @Test
+ void testOverflows()
+ {
+ long delay = new ExponentialBackoffRetryPolicy(1, 1, 0)
+ .retryDelayMillis(66); // 2 ^ 63 + 1 overflows
Review Comment:
updated comment, and added a new test 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.
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-sidecar] yifan-c commented on a diff in pull request #45: CEP-28: Implement Bulk API endpoints and introduce the Sidecar Client to Support Bulk Analytics
Posted by "yifan-c (via GitHub)" <gi...@apache.org>.
yifan-c commented on code in PR #45:
URL: https://github.com/apache/cassandra-sidecar/pull/45#discussion_r1195481284
##########
cassandra40/src/main/java/org/apache/cassandra/sidecar/cassandra40/TokenRangeReplicas.java:
##########
@@ -0,0 +1,515 @@
+/*
+ * 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.sidecar.cassandra40;
+
+import java.math.BigInteger;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Set;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import com.google.common.base.Objects;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.VisibleForTesting;
+
+
+/**
+ * Representation of a token range and the corresponding mapping to replica-set hosts. The range corresponds to
+ * an exclusive start range and inclusive end range {@code (start, end]}.
+ */
+public class TokenRangeReplicas implements Comparable<TokenRangeReplicas>
+{
+ private final BigInteger start;
+ private final BigInteger end;
+
+ private final Partitioner partitioner;
+
+ private final Set<String> replicaSet;
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(TokenRangeReplicas.class);
+
+ public TokenRangeReplicas(BigInteger start, BigInteger end, Partitioner partitioner, Set<String> replicaSet)
+ {
+ this.start = start;
+ this.end = end;
+ this.partitioner = partitioner;
+ this.replicaSet = replicaSet;
+ }
+
+
+ public BigInteger start()
+ {
+ return start;
+ }
+
+ public BigInteger end()
+ {
+ return end;
+ }
+
+ public Set<String> replicaSet()
+ {
+ return replicaSet;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public int compareTo(@NotNull TokenRangeReplicas other)
+ {
+ validateMatchingPartitioner(other);
+
+ BigInteger maxValue = this.partitioner.maxToken;
+ if (this.start.compareTo(other.start) == 0)
+ {
+ if (this.end.equals(maxValue)) return 1;
+ else if (other.end.equals(maxValue)) return -1;
+ else return this.end.compareTo(other.end);
+ }
+ else return this.start.compareTo(other.start);
Review Comment:
It looks wrong to me..
Say R1 (1, MAX] and R2 (1, MAX], apparently R1 == R2, but according to this implement `R1.compareTo(R2) == 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.
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-sidecar] frankgh commented on a diff in pull request #45: CEP-28: Implement Bulk API endpoints and introduce the Sidecar Client to Support Bulk Analytics
Posted by "frankgh (via GitHub)" <gi...@apache.org>.
frankgh commented on code in PR #45:
URL: https://github.com/apache/cassandra-sidecar/pull/45#discussion_r1194411769
##########
client/src/main/java/org/apache/cassandra/sidecar/client/exception/UnexpectedStatusCodeException.java:
##########
@@ -0,0 +1,53 @@
+/*
+ * 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.sidecar.client.exception;
+
+/**
+ * Represents an exception raised when an unexpected status code is encountered
+ */
+public class UnexpectedStatusCodeException extends RuntimeException
+{
+ /**
+ * Constructs a new {@link UnexpectedStatusCodeException} with the given {@code statusCode} and {@code body}
+ *
+ * @param statusCode the response status code
+ * @param body the body of the response
+ */
+ public UnexpectedStatusCodeException(int statusCode, String body)
Review Comment:
will leave for now as it's an unexpected case, what do you think?
--
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-sidecar] yifan-c commented on a diff in pull request #45: CEP-28: Implement Bulk API endpoints and introduce the Sidecar Client to Support Bulk Analytics
Posted by "yifan-c (via GitHub)" <gi...@apache.org>.
yifan-c commented on code in PR #45:
URL: https://github.com/apache/cassandra-sidecar/pull/45#discussion_r1194099633
##########
client/src/main/java/org/apache/cassandra/sidecar/client/retry/ExponentialBackoffRetryPolicy.java:
##########
@@ -0,0 +1,90 @@
+/*
+ * 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.sidecar.client.retry;
+
+/**
+ * A retry policy that will perform an exponential backoff. The backoff period increases for each retry attempt.
+ *
+ * <p>Example: For a configured {@code maxRetries} of {@code 10}, {@code retryDelayMillis} of {@code 200}
+ * milliseconds, and {@code maxRetryDelayMillis} of {@code 20,000} milliseconds, the sequence is as follows:
+ *
+ * <pre>
+ * request backoff
+ *
+ * 1 200
+ * 2 400
+ * 3 800
+ * 4 1600
+ * 5 3200
+ * 6 6400
+ * 7 12800
+ * 8 20000
+ * 9 20000
+ * 10 20000
+ * </pre>
+ */
+public class ExponentialBackoffRetryPolicy extends BasicRetryPolicy
+{
+ private final long maxRetryDelayMillis;
+
+ /**
+ * Constructs an exponential backoff retry policy unlimited number of retries and no delay between retries.
+ */
+ public ExponentialBackoffRetryPolicy()
+ {
+ super();
+ this.maxRetryDelayMillis = 0;
+ }
+
+ /**
+ * Constructs an exponential backoff retry policy with {@code maxRetries} number of retries,
+ * {@code retryDelayMillis} delay between retries, and {@code maxRetryDelayMillis} maximum delay for the
+ * exponential backoff.
+ *
+ * @param maxRetries the maximum number of retries
+ * @param retryDelayMillis the delay between retries in milliseconds
+ * @param maxRetryDelayMillis the maximum retry delay in milliseconds
+ */
+ public ExponentialBackoffRetryPolicy(int maxRetries, long retryDelayMillis, long maxRetryDelayMillis)
+ {
+ super(maxRetries, retryDelayMillis);
+ this.maxRetryDelayMillis = maxRetryDelayMillis;
+ }
+
+ /**
+ * Returns the number of milliseconds to wait before attempting the next request. This value is upper-bounded
+ * by {@code maxRetryDelayMillis} if configured. The delay increases exponentially based on the number of
+ * attempts already performed.
+ *
+ * @param attempts the number of attempts already performed for this request
+ * @return the number of milliseconds to wait before attempting the next request
+ */
+ @Override
+ protected long retryDelayMillis(int attempts)
+ {
+ long exponentialValue = (long) Math.pow(2, attempts - 1);
+ // do not multiply times retryDelayMillis, if we've reached the Long.MAX_VALUE already to avoid overflows
+ long retryDelay = exponentialValue == Long.MAX_VALUE ? exponentialValue : exponentialValue * retryDelayMillis;
Review Comment:
It will. Say `exponentialValue == Long.MAX_VALUE / 2` and `retryDelayMillis == 3`, and boom!
```shell
jshell> exponentialValue * retryDelayMillis
$10 ==> -4611686018427387907
```
--
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-sidecar] frankgh commented on a diff in pull request #45: CEP-28: Implement Bulk API endpoints and introduce the Sidecar Client to Support Bulk Analytics
Posted by "frankgh (via GitHub)" <gi...@apache.org>.
frankgh commented on code in PR #45:
URL: https://github.com/apache/cassandra-sidecar/pull/45#discussion_r1194109504
##########
client/src/main/java/org/apache/cassandra/sidecar/client/selection/OrderedInstanceSelectionPolicy.java:
##########
@@ -0,0 +1,54 @@
+/*
+ * 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.sidecar.client.selection;
+
+import java.util.Iterator;
+
+import org.apache.cassandra.sidecar.client.SidecarInstance;
+import org.apache.cassandra.sidecar.client.SidecarInstancesProvider;
+import org.jetbrains.annotations.NotNull;
+
+/**
+ * A selection policy for a multiple Cassandra Sidecar instances where the iterator returns in order
+ */
+public class OrderedInstanceSelectionPolicy implements InstanceSelectionPolicy
+{
+ protected final SidecarInstancesProvider instancesProvider;
+
+ /**
+ * Constructs a new {@link OrderedInstanceSelectionPolicy} with the provided list of instances
+ *
+ * @param instancesProvider the class that provides the sidecar instances
+ */
+ public OrderedInstanceSelectionPolicy(SidecarInstancesProvider instancesProvider)
+ {
+ this.instancesProvider = instancesProvider;
+ }
+
+ /**
+ * Returns an iterator of {@link SidecarInstance instances}.
+ *
+ * @return an iterator of {@link SidecarInstance instances}
+ */
+ @NotNull
+ public Iterator<SidecarInstance> iterator()
+ {
+ return instancesProvider.instances().iterator();
Review Comment:
what I can probably do for now is write a more descriptive javadoc. Let me know if that works 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.
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-sidecar] yifan-c commented on a diff in pull request #45: CEP-28: Implement Bulk API endpoints and introduce the Sidecar Client to Support Bulk Analytics
Posted by "yifan-c (via GitHub)" <gi...@apache.org>.
yifan-c commented on code in PR #45:
URL: https://github.com/apache/cassandra-sidecar/pull/45#discussion_r1194376151
##########
src/main/java/org/apache/cassandra/sidecar/concurrent/ConcurrencyLimiter.java:
##########
@@ -0,0 +1,112 @@
+/*
+ * 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.sidecar.concurrent;
+
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.IntSupplier;
+
+import com.google.common.annotations.VisibleForTesting;
+
+/**
+ * A class that provides functionality for a concurrency limiter where implementing consumers can try to acquire a
+ * permit before executing an operation, and later releasing the permit when the operation is completed. This
+ * implementation relies on clients playing fairly and not acquiring more permits or releasing more permits than they
+ * are allowed. This class is intended to be used on constrained resources, for example uploads to the server, where
+ * we want to limit the amount of concurrent uploads to the server, and if we are too busy, we want to provide a
+ * mechanism to deny new uploads until the server has been freed up.
+ *
+ * <p>The intended usage of this class is as follows:
+ *
+ * <pre>
+ * if (limiter.tryAcquire()) {
+ * try {
+ * // .. some expensive operation
+ * } finally {
+ * limiter.releasePermit();
+ * }
+ * } else {
+ * // .. handle the case where the limit has been reached
+ * }
+ * </pre>
+ *
+ * <p>In a vertx {@link io.vertx.core.Handler}, this can be implemented as follows:
+ *
+ * <pre>
+ * public void handle(RoutingContext context) {
+ * if (!limiter.tryAcquire()) {
+ * // handle the case where the limit has been reached
+ * return;
+ * }
+ * // to make sure that permit is always released
+ * context.addEndHandler(v -> limiter.releasePermit());
+ * // .. some expensive operation
+ * }
+ * </pre>
+ */
+public class ConcurrencyLimiter
+{
+ @VisibleForTesting
+ final AtomicInteger permits = new AtomicInteger(0);
Review Comment:
instead of exposing the mutable `AtomicInteger`, can you add a method to return the current `permits: int` and make the filed private instead?
```java
public int acquiredPermits()
{
return permits.get();
}
```
##########
src/main/java/org/apache/cassandra/sidecar/data/SchemaRequest.java:
##########
@@ -15,24 +15,34 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.cassandra.sidecar.common.data;
+package org.apache.cassandra.sidecar.data;
import org.jetbrains.annotations.Nullable;
/**
* Holder class for the {@link org.apache.cassandra.sidecar.routes.SchemaHandler}
* request parameters
*/
-public class SchemaRequest extends QualifiedTableName
+public class SchemaRequest
Review Comment:
Should we rename this group of classes to Payload in this patch? For this one, `SchemaRequestPayload`
##########
src/test/integration/org/apache/cassandra/sidecar/IntegrationTestBase.java:
##########
@@ -0,0 +1,131 @@
+/*
+ * 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.sidecar;
+
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.Consumer;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.datastax.driver.core.Session;
+import com.google.inject.Guice;
+import com.google.inject.Injector;
+import com.google.inject.util.Modules;
+import io.vertx.core.Vertx;
+import io.vertx.core.http.HttpServer;
+import io.vertx.ext.web.client.WebClient;
+import io.vertx.junit5.VertxTestContext;
+import org.apache.cassandra.sidecar.common.data.QualifiedTableName;
+import org.apache.cassandra.sidecar.common.testing.CassandraTestContext;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+/**
+ * Base class for integration test.
+ * Start a docker container of cassandra at the begining of each test, and
Review Comment:
```suggestion
* Start a docker container of cassandra at the beginning of each test, and
```
##########
src/main/java/org/apache/cassandra/sidecar/utils/MD5ChecksumVerifier.java:
##########
@@ -0,0 +1,101 @@
+/*
+ * 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.sidecar.utils;
+
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.util.Base64;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import io.netty.handler.codec.http.HttpResponseStatus;
+import io.vertx.core.Future;
+import io.vertx.core.Promise;
+import io.vertx.core.file.AsyncFile;
+import io.vertx.core.file.FileSystem;
+import io.vertx.core.file.OpenOptions;
+import io.vertx.ext.web.handler.HttpException;
+
+/**
+ * Implementation of {@link ChecksumVerifier}. Here we use MD5 implementation of {@link java.security.MessageDigest}
+ * for calculating checksum. And match the calculated checksum with expected checksum obtained from request.
+ */
+public class MD5ChecksumVerifier implements ChecksumVerifier
+{
+ private static final Logger LOGGER = LoggerFactory.getLogger(MD5ChecksumVerifier.class);
+ private final FileSystem fs;
+
+ public MD5ChecksumVerifier(FileSystem fs)
+ {
+ this.fs = fs;
+ }
+
+ public Future<String> verify(String expectedChecksum, String filePath)
+ {
+ if (expectedChecksum == null)
+ {
+ return Future.succeededFuture(filePath);
+ }
+
+ LOGGER.debug("Validating MD5. Expected to match: {}", expectedChecksum);
+
+ return fs.open(filePath, new OpenOptions())
+ .compose(this::calculateMD5)
+ .compose(computedChecksum -> {
+ if (!expectedChecksum.equals(computedChecksum))
+ return Future.failedFuture(new HttpException(HttpResponseStatus.BAD_REQUEST.code(),
+ String.format("Checksum mismatch. "
+ + "computed_checksum=%s, "
+ + "expected_checksum=%s, "
+ + "algorithm=MD5",
+ computedChecksum,
+ expectedChecksum)));
+ LOGGER.debug("Checksum mismatch. computed_checksum={}, expected_checksum={}, algorithm=MD5",
+ computedChecksum, expectedChecksum);
+ return Future.succeededFuture(filePath);
+ });
+ }
+
+ private Future<String> calculateMD5(AsyncFile file)
+ {
+ MessageDigest digest;
+ try
+ {
+ digest = MessageDigest.getInstance("MD5");
+ }
+ catch (NoSuchAlgorithmException e)
+ {
+ return Future.failedFuture(e);
+ }
+
+ Promise<String> result = Promise.promise();
+ file.pause()
+ .setReadBufferSize(64 * 1024)
Review Comment:
Declare a constant for the buffer size?
##########
src/main/java/org/apache/cassandra/sidecar/routes/FileStreamHandler.java:
##########
@@ -24,54 +24,60 @@
import com.google.inject.Inject;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.vertx.core.Future;
-import io.vertx.core.Handler;
import io.vertx.core.file.FileProps;
import io.vertx.core.file.FileSystem;
import io.vertx.core.http.HttpServerRequest;
+import io.vertx.core.net.SocketAddress;
import io.vertx.ext.web.RoutingContext;
-import io.vertx.ext.web.handler.HttpException;
+import org.apache.cassandra.sidecar.concurrent.ExecutorPools;
import org.apache.cassandra.sidecar.models.HttpResponse;
import org.apache.cassandra.sidecar.utils.FileStreamer;
+import org.apache.cassandra.sidecar.utils.InstanceMetadataFetcher;
import static io.netty.handler.codec.http.HttpResponseStatus.NOT_FOUND;
import static io.netty.handler.codec.http.HttpResponseStatus.REQUESTED_RANGE_NOT_SATISFIABLE;
-import static org.apache.cassandra.sidecar.utils.RequestUtils.extractHostAddressWithoutPort;
+import static org.apache.cassandra.sidecar.utils.HttpExceptions.wrapHttpException;
/**
* Handler for sending out files.
*/
-public class FileStreamHandler implements Handler<RoutingContext>
+public class FileStreamHandler extends AbstractHandler<String>
{
- private static final Logger LOGGER = LoggerFactory.getLogger(FileStreamHandler.class);
public static final String FILE_PATH_CONTEXT_KEY = "fileToTransfer";
-
+ private static final Logger LOGGER = LoggerFactory.getLogger(FileStreamHandler.class);
Review Comment:
logger defined in base class already
##########
common/src/test/java/org/apache/cassandra/sidecar/common/SimpleCassandraVersionProviderTest.java:
##########
@@ -78,7 +78,7 @@ void ensureOutOfOrderInsertionWorks()
.add(new V41())
.add(new V30()).build();
- ICassandraFactory cassandra = provider.getCassandra(SimpleCassandraVersion.create("4.0.0"));
+ ICassandraFactory cassandra = provider.cassandra(SimpleCassandraVersion.create("4.0.0"));
assertThat(cassandra).hasSameClassAs(new V40());
Review Comment:
To test `ensureOutOfOrderInsertionWorks`, should it get V30 from version `SimpleCassandraVersion.create("3.0.0")`?
After I made the change, it actually fails, meaning the insertion order has to be in the ascending order of the versions. Either updating the test case or the implementation of builder is needed.
##########
src/main/java/org/apache/cassandra/sidecar/utils/CacheFactory.java:
##########
@@ -0,0 +1,101 @@
+/*
+ * 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.sidecar.utils;
+
+import java.time.Duration;
+import java.time.temporal.ChronoUnit;
+
+import com.google.common.util.concurrent.MoreExecutors;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.github.benmanes.caffeine.cache.Cache;
+import com.github.benmanes.caffeine.cache.Caffeine;
+import com.github.benmanes.caffeine.cache.RemovalListener;
+import com.github.benmanes.caffeine.cache.Ticker;
+import com.google.inject.Inject;
+import com.google.inject.Singleton;
+import io.vertx.core.Future;
+import org.apache.cassandra.sidecar.Configuration;
+import org.apache.cassandra.sidecar.config.CacheConfiguration;
+import org.jetbrains.annotations.VisibleForTesting;
+
+/**
+ * A factory for caches used in Sidecar
+ */
+@Singleton
+public class CacheFactory
+{
+ private static final Logger LOGGER = LoggerFactory.getLogger(CacheFactory.class);
+
+ private final Cache<SSTableImporter.ImportOptions, Future<Void>> ssTableImportCache;
+
+ @Inject
+ public CacheFactory(Configuration configuration, SSTableImporter ssTableImporter)
+ {
+ this(configuration, ssTableImporter, Ticker.systemTicker());
+ }
+
+ @VisibleForTesting
+ CacheFactory(Configuration configuration, SSTableImporter ssTableImporter, Ticker ticker)
+ {
+ this.ssTableImportCache = initSSTableImportCache(configuration.ssTableImportCacheConfiguration(),
+ ssTableImporter, ticker);
+ }
+
+ /**
+ * @return the cache used for the SSTableImport requests
+ */
+ public Cache<SSTableImporter.ImportOptions, Future<Void>> ssTableImportCache()
+ {
+ return ssTableImportCache;
+ }
+
+ /**
+ * Initializes the SSTable Import Cache using the provided {@code configuration} and {@code ticker}
+ * for the cache
+ *
+ * @param configuration the Cache configuration parameters
+ * @param ssTableImporter the reference to the SSTable importer singleton
+ * @param ticker the ticker for the cache
+ * @return the initialized cache
+ */
+ protected Cache<SSTableImporter.ImportOptions, Future<Void>>
+ initSSTableImportCache(CacheConfiguration configuration, SSTableImporter ssTableImporter, Ticker ticker)
+ {
+ Duration expireAfterAccessDuration = Duration.of(configuration.expireAfterAccessMillis(), ChronoUnit.MILLIS);
+ long maximumSize = configuration.maximumSize();
+ LOGGER.info("Building SSTable Import Cache with expireAfterAccess={}, maxSize={}",
+ expireAfterAccessDuration, maximumSize);
+ return Caffeine.newBuilder()
+ .ticker(ticker)
+ .executor(MoreExecutors.directExecutor())
+ .expireAfterAccess(expireAfterAccessDuration)
+ .maximumSize(maximumSize)
+ .recordStats()
+ .removalListener((RemovalListener<SSTableImporter.ImportOptions, Future<Void>>)
+ (options, result, cause) -> {
+ LOGGER.debug("Removed entry '{}' with options '{}' from SSTable Import " +
+ "Cache and cause {}", result, options, cause);
Review Comment:
```suggestion
"Cache and cause {}", result, options, cause);
```
##########
src/main/java/org/apache/cassandra/sidecar/cluster/instance/InstanceMetadata.java:
##########
@@ -50,14 +48,9 @@
List<String> dataDirs();
/**
- * @return {@link CQLSession} for connecting with instance via CQL
+ * @return staging directory for the uploads of the cassandra instance
*/
- CQLSession session();
-
- /**
- * @return {@link JmxClient} for connecting with the instance via JMX
- */
- JmxClient jmxClient();
+ String uploadsStagingDir();
Review Comment:
Can you call it `stagingDir`? It is just a directory for the staging data, not necessary to distinguish between scenarios like upload or others.
##########
src/main/java/org/apache/cassandra/sidecar/routes/SnapshotsHandler.java:
##########
@@ -0,0 +1,364 @@
+/*
+ * 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.sidecar.routes;
+
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.lang.reflect.UndeclaredThrowableException;
+import java.nio.file.NoSuchFileException;
+import java.util.List;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableMap;
+import org.apache.commons.lang3.StringUtils;
+
+import com.google.inject.Inject;
+import com.google.inject.Singleton;
+import io.netty.handler.codec.http.HttpResponseStatus;
+import io.vertx.core.http.HttpMethod;
+import io.vertx.core.http.HttpServerRequest;
+import io.vertx.core.json.JsonObject;
+import io.vertx.core.net.SocketAddress;
+import io.vertx.ext.web.RoutingContext;
+import io.vertx.ext.web.handler.HttpException;
+import org.apache.cassandra.sidecar.Configuration;
+import org.apache.cassandra.sidecar.common.CassandraAdapterDelegate;
+import org.apache.cassandra.sidecar.common.StorageOperations;
+import org.apache.cassandra.sidecar.common.data.ListSnapshotFilesResponse;
+import org.apache.cassandra.sidecar.common.utils.CassandraInputValidator;
+import org.apache.cassandra.sidecar.concurrent.ExecutorPools;
+import org.apache.cassandra.sidecar.data.SnapshotRequest;
+import org.apache.cassandra.sidecar.snapshots.SnapshotDirectory;
+import org.apache.cassandra.sidecar.snapshots.SnapshotPathBuilder;
+import org.apache.cassandra.sidecar.utils.InstanceMetadataFetcher;
+
+import static org.apache.cassandra.sidecar.utils.HttpExceptions.cassandraServiceUnavailable;
+import static org.apache.cassandra.sidecar.utils.HttpExceptions.wrapHttpException;
+
+/**
+ * The SnapshotsHandler class handles snapshot operations.
+ *
+ * <ul>
+ * <li>
+ * The <b>GET</b> verb will produce a list of paths of all the snapshot files of a given
+ * snapshot name.
+ * <p>
+ * The query param {@code includeSecondaryIndexFiles} is used to request secondary index
+ * files along with other files. For example:
+ * <p>
+ * {@code /api/v1/keyspaces/ks/tables/tbl/snapshots/testSnapshot}
+ * lists all SSTable component files for the <i>"testSnapshot"</i> snapshot for the
+ * <i>"ks"</i> keyspace and the <i>"tbl"</i> table
+ * <p>
+ * {@code /api/v1/keyspaces/ks/tables/tbl/snapshots/testSnapshot?includeSecondaryIndexFiles=true}
+ * lists all SSTable component files, including secondary index files, for the
+ * <i>"testSnapshot"</i> snapshot for the <i>"ks"</i> keyspace and the <i>"tbl"</i> table
+ * </li>
+ * <li>
+ * The <b>PUT</b> verb creates a new snapshot for the given keyspace and table
+ * </li>
+ * <li>
+ * The <b>DELETE</b> verb deletes an existing snapshot for the given keyspace and table
+ * </li>
+ * </ul>
+ */
+@Singleton
+public class SnapshotsHandler extends AbstractHandler<SnapshotRequest>
+{
+ private static final String INCLUDE_SECONDARY_INDEX_FILES = "includeSecondaryIndexFiles";
+ private final SnapshotPathBuilder builder;
+ private final Configuration configuration;
+
+ @Inject
+ public SnapshotsHandler(SnapshotPathBuilder builder,
+ Configuration configuration,
+ InstanceMetadataFetcher metadataFetcher,
+ CassandraInputValidator validator,
+ ExecutorPools executorPools)
+ {
+ super(metadataFetcher, executorPools, validator);
+ this.builder = builder;
+ this.configuration = configuration;
+ }
+
+ @Override
+ public void handleInternal(RoutingContext context,
+ HttpServerRequest httpRequest,
+ String host,
+ SocketAddress remoteAddress,
+ SnapshotRequest request)
+ {
+ HttpMethod method = context.request().method();
+ if (method.equals(HttpMethod.GET))
+ {
+ listSnapshot(context, host, remoteAddress, request);
+ }
+ else if (method.equals(HttpMethod.PUT))
+ {
+ createSnapshot(context, host, remoteAddress, request);
+ }
+ else if (method.equals(HttpMethod.DELETE))
+ {
+ clearSnapshot(context, host, remoteAddress, request);
+ }
+ else
+ {
+ throw new UnsupportedOperationException("Method " + context.request().method() + " is not supported");
+ }
+ }
+
+ /**
+ * Lists paths of all the snapshot files of a given snapshot name.
+ * <p>
+ * The query param {@code includeSecondaryIndexFiles} is used to request secondary index
+ * files along with other files. For example:
+ * <p>
+ * {@code /api/v1/keyspaces/ks/tables/tbl/snapshots/testSnapshot}
+ * lists all SSTable component files for the <i>"testSnapshot"</i> snapshot for the
+ * <i>"ks"</i> keyspace and the <i>"tbl"</i> table
+ * <p>
+ * {@code /api/v1/keyspaces/ks/tables/tbl/snapshots/testSnapshot?includeSecondaryIndexFiles=true}
+ * lists all SSTable component files, including secondary index files, for the
+ * <i>"testSnapshot"</i> snapshot for the <i>"ks"</i> keyspace and the <i>"tbl"</i> table
+ *
+ * @param context the event to handle
+ * @param host the name of the host
+ * @param remoteAddress the remote address that originated the request
+ * @param requestParams parameters obtained from the request
+ */
+ private void listSnapshot(RoutingContext context,
+ String host,
+ SocketAddress remoteAddress,
+ SnapshotRequest requestParams)
+ {
+ builder.build(host, requestParams)
+ .onSuccess(snapshotDirectory ->
+ builder.listSnapshotDirectory(snapshotDirectory, requestParams.includeSecondaryIndexFiles())
+ .onSuccess(fileList -> {
+ if (fileList.isEmpty())
+ {
+ String payload = "Snapshot '" + requestParams.snapshotName() + "' not found";
+ context.fail(wrapHttpException(HttpResponseStatus.NOT_FOUND, payload));
+ }
+ else
+ {
+ logger.debug("SnapshotsHandler handled request={}, remoteAddress={}, " +
+ "instance={}", requestParams, remoteAddress, host);
+ context.json(buildResponse(host, snapshotDirectory, fileList));
+ }
+ })
+ .onFailure(cause -> processFailure(cause, context, host, remoteAddress, requestParams))
+ )
+ .onFailure(cause -> processFailure(cause, context, host, remoteAddress, requestParams));
+ }
+
+ @Override
+ protected void processFailure(Throwable cause,
+ RoutingContext context,
+ String host,
+ SocketAddress remoteAddress,
+ SnapshotRequest requestParams)
+ {
+ logger.error("SnapshotsHandler failed for request={}, remoteAddress={}, instance={}, method={}",
+ requestParams, remoteAddress, host, context.request().method(), cause);
+ if (cause instanceof FileNotFoundException || cause instanceof NoSuchFileException)
+ {
+ context.fail(wrapHttpException(HttpResponseStatus.NOT_FOUND, cause.getMessage()));
+ }
+ else if (cause instanceof HttpException)
+ {
+ context.fail(cause);
+ }
+ else
+ {
+ context.fail(wrapHttpException(HttpResponseStatus.BAD_REQUEST, "Invalid request for " + requestParams));
+ }
+ }
+
+ private ListSnapshotFilesResponse buildResponse(String host,
+ String snapshotDirectory,
+ List<SnapshotPathBuilder.SnapshotFile> fileList)
+ {
+ ListSnapshotFilesResponse response = new ListSnapshotFilesResponse();
+ int sidecarPort = configuration.getPort();
+ SnapshotDirectory directory = SnapshotDirectory.of(snapshotDirectory);
+ int dataDirectoryIndex = dataDirectoryIndex(host, directory.dataDirectory);
+ int offset = snapshotDirectory.length() + 1;
+
+ for (SnapshotPathBuilder.SnapshotFile snapshotFile : fileList)
+ {
+ int fileNameIndex = snapshotFile.path.indexOf(snapshotDirectory) + offset;
+ Preconditions.checkArgument(fileNameIndex < snapshotFile.path.length(),
+ "Invalid snapshot file '" + snapshotFile.path + "'");
+ response.addSnapshotFile(
+ new ListSnapshotFilesResponse.FileInfo(snapshotFile.size,
+ host,
+ sidecarPort,
+ dataDirectoryIndex,
+ directory.snapshotName,
+ directory.keyspace,
+ directory.tableName,
+ snapshotFile.path.substring(fileNameIndex)));
+ }
+ return response;
+ }
+
+ /**
+ * Creates a new snapshot for the given keyspace and table.
+ *
+ * @param context the event to handle
+ * @param host the name of the host
+ * @param remoteAddress the remote address that originated the request
+ * @param requestParams parameters obtained from the request
+ */
+ private void createSnapshot(RoutingContext context,
+ String host,
+ SocketAddress remoteAddress,
+ SnapshotRequest requestParams)
+ {
+ ExecutorPools.TaskExecutorPool pool = executorPools.service();
+ pool.executeBlocking(promise -> {
+ CassandraAdapterDelegate delegate = metadataFetcher.delegate(host(context));
+ StorageOperations storageOperations = delegate.storageOperations();
+ if (storageOperations == null)
+ throw cassandraServiceUnavailable();
+ logger.debug("Creating snapshot request={}, remoteAddress={}, instance={}",
+ requestParams, remoteAddress, host);
+ storageOperations.takeSnapshot(requestParams.snapshotName(), requestParams.keyspace(),
+ requestParams.tableName(), ImmutableMap.of());
+ JsonObject jsonObject = new JsonObject()
+ .put("result", "Success");
+ context.json(jsonObject);
+ })
+ .onFailure(cause -> processCreateSnapshotFailure(cause, context, requestParams, remoteAddress, host));
+ }
+
+ private void processCreateSnapshotFailure(Throwable cause, RoutingContext context, SnapshotRequest requestParams,
+ SocketAddress remoteAddress, String host)
+ {
+ logger.error("SnapshotsHandler failed for request={}, remoteAddress={}, instance={}, method={}",
+ requestParams, remoteAddress, host, context.request().method(), cause);
+
+ Throwable rootCause = cause instanceof UndeclaredThrowableException
+ ? ((UndeclaredThrowableException) cause).getUndeclaredThrowable()
+ : cause;
+
+ if (rootCause instanceof IOException)
+ {
+ if (StringUtils.contains(rootCause.getMessage(),
+ "Snapshot " + requestParams.snapshotName() + " already exists"))
+ {
+ context.fail(wrapHttpException(HttpResponseStatus.CONFLICT, rootCause.getMessage()));
+ return;
+ }
+ else if (StringUtils.contains(rootCause.getMessage(),
+ "Cannot snapshot until bootstrap completes"))
+ {
+ // Cassandra does not allow taking snapshots while the node is JOINING the ring
+ context.fail(wrapHttpException(HttpResponseStatus.SERVICE_UNAVAILABLE,
+ "The Cassandra instance " + host + " is not available"));
+ }
+ }
+ else if (rootCause instanceof IllegalArgumentException)
+ {
+ if (StringUtils.contains(rootCause.getMessage(),
+ "Keyspace " + requestParams.keyspace() + " does not exist") ||
+ StringUtils.contains(rootCause.getMessage(),
+ "Unknown keyspace/cf pair"))
+ {
+ context.fail(wrapHttpException(HttpResponseStatus.NOT_FOUND, rootCause.getMessage()));
+ }
+ else
+ {
+ context.fail(wrapHttpException(HttpResponseStatus.BAD_REQUEST, rootCause.getMessage()));
+ }
+ return;
+ }
+ context.fail(wrapHttpException(HttpResponseStatus.BAD_REQUEST, "Invalid request for " + requestParams));
+ }
+
+ /**
+ * Clears a snapshot for the given keyspace and table. **Note**: Currently, Cassandra does not support
+ * the table parameter. We can add support in Cassandra for the additional parameter.
+ *
+ * @param context the event to handle
+ * @param host the name of the host
+ * @param remoteAddress the remote address that originated the request
+ * @param requestParams parameters obtained from the request
+ */
+ private void clearSnapshot(RoutingContext context,
+ String host,
+ SocketAddress remoteAddress,
+ SnapshotRequest requestParams)
+ {
+ // Leverage the SnapshotBuilder for validation purposes. Currently, JMX does not validate for
+ // non-existent snapshot name or keyspace. Additionally, the current JMX implementation to clear snapshots
+ // does not support passing a table as a parameter.
+ builder.build(host, requestParams)
+ .compose(snapshotDirectory ->
+ executorPools.service().executeBlocking(promise -> {
+ CassandraAdapterDelegate delegate =
+ metadataFetcher.delegate(host(context));
+ StorageOperations storageOperations = delegate.storageOperations();
+ if (storageOperations == null)
+ throw cassandraServiceUnavailable();
+ logger.debug("Clearing snapshot request={}, remoteAddress={}, instance={}",
+ requestParams, remoteAddress, host);
+ storageOperations.clearSnapshot(requestParams.snapshotName(), requestParams.keyspace(),
+ requestParams.tableName());
+ context.response().end();
+ }))
+ .onFailure(cause -> processFailure(cause, context, host, remoteAddress, requestParams));
+ }
+
+ private int dataDirectoryIndex(String host, String dataDirectory)
+ {
+ List<String> dataDirs = metadataFetcher.instance(host).dataDirs();
+ for (int index = 0; index < dataDirs.size(); index++)
+ {
+ if (dataDirectory.startsWith(dataDirs.get(index)))
+ {
+ return index;
+ }
+ }
+ return -1;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ protected SnapshotRequest extractParamsOrThrow(final RoutingContext context)
+ {
+ boolean includeSecondaryIndexFiles =
+ "true".equalsIgnoreCase(context.request().getParam(INCLUDE_SECONDARY_INDEX_FILES, "false"));
Review Comment:
nit
```suggestion
boolean includeSecondaryIndexFiles = Boolean.parseBoolean(context.request().getParam(INCLUDE_SECONDARY_INDEX_FILES, "false"));
```
##########
src/main/java/org/apache/cassandra/sidecar/utils/RequestUtils.java:
##########
@@ -18,30 +18,29 @@
package org.apache.cassandra.sidecar.utils;
+import io.vertx.core.http.HttpServerRequest;
+
/**
* Utility class for Http request related operations.
*/
public class RequestUtils
{
/**
- * Given a combined host address like 127.0.0.1:9042 or [2001:db8:0:0:0:ff00:42:8329]:9042, this method
- * removes port information and returns 127.0.0.1 or 2001:db8:0:0:0:ff00:42:8329.
- * @param address
- * @return host address without port information
+ * Parses a boolean parameter from the {@code request}, for the given {@code headerName}. If the request param
+ * is not {@code true} or {@code false}, it returns the {@code defaultValue}.
+ *
+ * @param request the request
+ * @param headerName the name of the header
+ * @param defaultValue the default value when the request parameter does not match {@code true} or {@code false}
+ * @return the parsed value for the {@code headerName} from the {@code request}
*/
- public static String extractHostAddressWithoutPort(String address)
+ public static boolean parseBooleanHeader(HttpServerRequest request, String headerName, boolean defaultValue)
{
- if (address.contains(":"))
- {
- // just ipv6 host name present without port information
- if (address.split(":").length > 2 && !address.startsWith("["))
- {
- return address;
- }
- String host = address.substring(0, address.lastIndexOf(':'));
- // remove brackets from ipv6 addresses
- return host.startsWith("[") ? host.substring(1, host.length() - 1) : host;
- }
- return address;
+ String value = request.getParam(headerName);
+ if ("true".equalsIgnoreCase(value))
+ return true;
+ if ("false".equalsIgnoreCase(value))
+ return false;
+ return defaultValue;
Review Comment:
Use `Boolean.parseBoolean()` instead?
##########
src/main/java/org/apache/cassandra/sidecar/routes/sstableuploads/SSTableCleanupHandler.java:
##########
@@ -0,0 +1,110 @@
+/*
+ * 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.sidecar.routes.sstableuploads;
+
+import java.nio.file.NoSuchFileException;
+
+import com.google.inject.Inject;
+import io.netty.handler.codec.http.HttpResponseStatus;
+import io.vertx.core.http.HttpMethod;
+import io.vertx.core.http.HttpServerRequest;
+import io.vertx.core.net.SocketAddress;
+import io.vertx.ext.web.RoutingContext;
+import org.apache.cassandra.sidecar.concurrent.ExecutorPools;
+import org.apache.cassandra.sidecar.routes.AbstractHandler;
+import org.apache.cassandra.sidecar.utils.InstanceMetadataFetcher;
+import org.apache.cassandra.sidecar.utils.SSTableUploadsPathBuilder;
+
+import static org.apache.cassandra.sidecar.utils.HttpExceptions.wrapHttpException;
+
+/**
+ * Manages cleaning up uploaded SSTables
+ */
+public class SSTableCleanupHandler extends AbstractHandler<String>
+{
+ private static final String UPLOAD_ID_PARAM = "uploadId";
+ private final SSTableUploadsPathBuilder uploadPathBuilder;
+
+ /**
+ * Constructs a handler with the provided {@code metadataFetcher}
+ *
+ * @param metadataFetcher the instance metadata fetcher
+ * @param uploadPathBuilder a class that provides SSTableUploads directories
+ * @param executorPools executor pools for blocking executions
+ */
+ @Inject
+ protected SSTableCleanupHandler(InstanceMetadataFetcher metadataFetcher,
+ SSTableUploadsPathBuilder uploadPathBuilder,
+ ExecutorPools executorPools)
+ {
+ super(metadataFetcher, executorPools, null);
+ this.uploadPathBuilder = uploadPathBuilder;
+ }
+
+ /**
+ * Handles cleaning up the SSTable upload staging directory
+ *
+ * @param context the context for the handler
+ */
+ @Override
+ public void handleInternal(RoutingContext context,
+ HttpServerRequest httpRequest,
+ String host,
+ SocketAddress remoteAddress,
+ String uploadId)
+ {
+ if (context.request().method() != HttpMethod.DELETE)
+ {
+ context.fail(wrapHttpException(HttpResponseStatus.BAD_REQUEST, "Unknown API requested"));
+ return;
+ }
Review Comment:
Why would the request router route such request? It is only reregistered for `delete`
##########
src/main/java/org/apache/cassandra/sidecar/utils/BaseFileSystem.java:
##########
@@ -0,0 +1,125 @@
+/*
+ * 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.sidecar.utils;
+
+import java.nio.file.NoSuchFileException;
+import java.util.List;
+import java.util.function.Predicate;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import io.vertx.core.Future;
+import io.vertx.core.file.FileProps;
+import io.vertx.core.file.FileSystem;
+import org.apache.cassandra.sidecar.cluster.InstancesConfig;
+import org.apache.cassandra.sidecar.common.utils.CassandraInputValidator;
+import org.apache.cassandra.sidecar.concurrent.ExecutorPools;
+
+/**
+ * Provides functionality for filesytem operations
Review Comment:
```suggestion
* Provides functionality for filesystem operations
```
##########
vertx-client-shaded/build.gradle:
##########
@@ -0,0 +1,123 @@
+/*
+ * 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.
+ */
+
+/**
+ * The sole purpose of this sub-project is to produce a shaded package for the vertx-client. Currently,
+ * the shadow plugin has some limitations when producing a non-shaded and shaded versions of the jar.
+ */
+
+import com.github.jengelman.gradle.plugins.shadow.transformers.CacheableTransformer
+import com.github.jengelman.gradle.plugins.shadow.transformers.Transformer
+import com.github.jengelman.gradle.plugins.shadow.transformers.TransformerContext
+import shadow.org.apache.tools.zip.ZipEntry
+import shadow.org.apache.tools.zip.ZipOutputStream
+
+plugins {
+ id('java-library')
+ id('maven-publish')
+ id('com.github.johnrengelman.shadow') version '6.1.0'
+}
+
+group 'org.apache.cassandra.sidecar'
+version project.version
+
+sourceCompatibility = 1.8
+
+configurations {
+ all*.exclude(group: 'ch.qos.logback')
+}
+
+dependencies {
+ shadow(group: 'org.slf4j', name: 'slf4j-api', version: "${project.slf4jVersion}")
+ shadow(group: 'com.fasterxml.jackson.core', name: 'jackson-annotations', version: '2.14.2')
+ api(project(':vertx-client'))
+}
+
+// Relocating a Package
+shadowJar {
+ archiveClassifier.set('')
+ relocate 'com.fasterxml.jackson.core', 'o.a.c.sidecar.client.shaded.com.fasterxml.jackson.core'
+ relocate 'com.fasterxml.jackson.databind', 'o.a.c.sidecar.client.shaded.com.fasterxml.jackson.databind'
+ relocate 'io.netty', 'o.a.c.sidecar.client.shaded.io.netty'
+ relocate 'io.vertx', 'o.a.c.sidecar.client.shaded.io.vertx'
+ relocate 'META-INF/native/libnetty', 'META-INF/native/sidecar_client_netty_shaded_netty'
+ relocate 'META-INF/native/netty', 'META-INF/native/io_sidecar_client_netty_shaded_netty'
+ relocate 'META-INF/versions/11/io/vertx', 'META-INF/versions/11/o/a/c/sidecar/client/shaded/io/vertx'
+ transform(NettyResourceTransformer.class)
+ mergeServiceFiles()
+
+ dependencies {
+ exclude(dependency('org.slf4j:.*:.*'))
+ // Exclude the jackson-annotations dependency so that extension clients can keep annotating POJOs
+ // without the need to use shadow annotations. For example, they can continue using
+ // com.fasterxml.jackson.annotation.JsonProperty.
+ exclude(dependency('com.fasterxml.jackson.core:jackson-annotations:.*'))
+ }
+}
+
+publishing {
+ publications {
+ shadow(MavenPublication) { publication ->
+ project.shadow.component(publication)
+
+ groupId project.group
+ artifactId "vertx-client-all"
+ version System.getenv("CODE_VERSION") ?: "${version}"
+ }
+ }
+}
+
+/**
+ * A Transformer which updates the Netty JAR META-INF/ resources to accurately
+ * reference shaded class names.
+ */
+@CacheableTransformer
+class NettyResourceTransformer implements Transformer {
Review Comment:
MAGIC!
##########
src/main/java/org/apache/cassandra/sidecar/utils/SSTableImporter.java:
##########
@@ -0,0 +1,587 @@
+/*
+ * 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.sidecar.utils;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.concurrent.ConcurrentLinkedQueue;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.function.Predicate;
+
+import org.apache.commons.lang3.tuple.Pair;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.inject.Inject;
+import com.google.inject.Singleton;
+import io.netty.handler.codec.http.HttpResponseStatus;
+import io.vertx.core.Future;
+import io.vertx.core.Promise;
+import io.vertx.core.Vertx;
+import io.vertx.ext.web.handler.HttpException;
+import org.apache.cassandra.sidecar.Configuration;
+import org.apache.cassandra.sidecar.common.CassandraAdapterDelegate;
+import org.apache.cassandra.sidecar.common.TableOperations;
+import org.apache.cassandra.sidecar.concurrent.ExecutorPools;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.VisibleForTesting;
+
+/**
+ * This class is in charge of performing SSTable imports into the desired Cassandra instance.
+ * Since imports are synchronized in the Cassandra side on a per table-basis, we only perform one import per
+ * Cassandra instance's keyspace/table, and we queue the rest of the import requests.
+ */
+@Singleton
+public class SSTableImporter
+{
+ private static final Logger LOGGER = LoggerFactory.getLogger(SSTableImporter.class);
+ public static final boolean DEFAULT_RESET_LEVEL = true;
+ public static final boolean DEFAULT_CLEAR_REPAIRED = true;
+ public static final boolean DEFAULT_VERIFY_SSTABLES = true;
+ public static final boolean DEFAULT_VERIFY_TOKENS = true;
+ public static final boolean DEFAULT_INVALIDATE_CACHES = true;
+ public static final boolean DEFAULT_EXTENDED_VERIFY = true;
+ public static final boolean DEFAULT_COPY_DATA = false;
+ private final Vertx vertx;
+ private final ExecutorPools executorPools;
+ private final InstanceMetadataFetcher metadataFetcher;
+ private final SSTableUploadsPathBuilder uploadPathBuilder;
+ @VisibleForTesting
+ final Map<String, ImportQueue> importQueuePerHost;
+
+ /**
+ * Constructs a new instance of the SSTableImporter class
+ *
+ * @param vertx the vertx instance
+ * @param metadataFetcher a class for fetching InstanceMetadata
+ * @param configuration the configuration for Sidecar
+ * @param executorPools the executor pool
+ * @param uploadPathBuilder a class that provides SSTableUploads directories
+ */
+ @Inject
+ SSTableImporter(Vertx vertx,
+ InstanceMetadataFetcher metadataFetcher,
+ Configuration configuration,
+ ExecutorPools executorPools,
+ SSTableUploadsPathBuilder uploadPathBuilder)
+ {
+ this.vertx = vertx;
+ this.executorPools = executorPools;
+ this.metadataFetcher = metadataFetcher;
+ this.uploadPathBuilder = uploadPathBuilder;
+ this.importQueuePerHost = new HashMap<>();
+ executorPools.internal()
+ .setPeriodic(configuration.getSSTableImportPollIntervalMillis(), this::processPendingImports);
+ }
+
+ /**
+ * Queues an import with the provided import {@code options} to be processed asynchronously. The imports
+ * are queued in a FIFO queue.
+ *
+ * @param options import options
+ * @return a future for the result of the import
+ */
+ public Future<Void> scheduleImport(ImportOptions options)
+ {
+ Promise<Void> promise = Promise.promise();
+ importQueuePerHost.computeIfAbsent(key(options), this::initializeQueue)
+ .offer(Pair.of(promise, options));
+ return promise.future();
+ }
+
+ /**
+ * Attempts to cancel an import for the provided {@code options}. This is a best-effort attempt, and
+ * if the import has been started, it will not be cancelled.
+ *
+ * @param options import options
+ * @return true if the options were removed from the queue, false otherwise
+ */
+ public boolean cancelImport(ImportOptions options)
+ {
+ ImportQueue queue = importQueuePerHost.get(key(options));
+ boolean removed = false;
+ if (queue != null)
+ {
+ removed = queue.removeIf(tuple -> options.equals(tuple.getRight()));
+ }
+
+ LOGGER.debug("Cancel import for options={} was {}removed", options, removed ? "" : "not ");
+ return removed;
+ }
+
+ /**
+ * Returns a key for the queues for the given {@code options}. Classes extending from {@link SSTableImporter}
+ * can override the {@link #key(ImportOptions)} method and provide a different key for the queue.
+ *
+ * @param options the import options
+ * @return a key for the queues for the given {@code options}
+ */
+ protected String key(ImportOptions options)
+ {
+ return options.host + "$" + options.keyspace + "$" + options.tableName;
+ }
+
+ /**
+ * Returns a new queue for the given {@code key}. Classes extending from {@link SSTableImporter} can override
+ * this method and provide a different implementation for the queue.
+ *
+ * @param key the key for the map
+ * @return a new queue for the given {@code key}
+ */
+ protected ImportQueue initializeQueue(String key)
+ {
+ return new ImportQueue();
+ }
+
+ /**
+ * Processes pending imports for every host in the import queue.
+ *
+ * @param timerId a unique identifier for the periodic timer
+ */
+ private void processPendingImports(Long timerId)
+ {
+ for (ImportQueue queue : importQueuePerHost.values())
+ {
+ if (!queue.isEmpty())
+ {
+ executorPools.internal()
+ .executeBlocking(p -> maybeDrainImportQueue(queue));
+ }
+ }
+ }
+
+ /**
+ * Tries to lock the queue to perform the draining. If the queue is already being drained, then it will
+ * not perform any operation.
+ *
+ * @param queue a queue of import tasks
+ */
+ private void maybeDrainImportQueue(ImportQueue queue)
+ {
+ if (queue.tryLock())
+ {
+ try
+ {
+ drainImportQueue(queue);
+ }
+ finally
+ {
+ queue.unlock();
+ }
+ }
+ }
+
+ /**
+ * This blocking operation will drain the {@code queue}. It will utilize a single thread
+ * to import the pending import requests on that host.
+ *
+ * @param queue a queue of import tasks
+ */
+ private void drainImportQueue(ImportQueue queue)
+ {
+ while (!queue.isEmpty())
+ {
+ Pair<Promise<Void>, ImportOptions> pair = queue.poll();
+ Promise<Void> promise = pair.getLeft();
+ ImportOptions options = pair.getRight();
+
+ CassandraAdapterDelegate cassandra = metadataFetcher.delegate(options.host);
+ TableOperations tableOperations = cassandra.tableOperations();
+
+ if (tableOperations == null)
+ {
+ promise.fail(new HttpException(HttpResponseStatus.SERVICE_UNAVAILABLE.code(),
+ "Cassandra service is unavailable"));
+ }
+ else
+ {
+ try
+ {
+ List<String> failedDirectories =
+ tableOperations.importNewSSTables(options.keyspace,
+ options.tableName,
+ options.directory,
+ options.resetLevel,
+ options.clearRepaired,
+ options.verifySSTables,
+ options.verifyTokens,
+ options.invalidateCaches,
+ options.extendedVerify,
+ options.copyData);
+ if (!failedDirectories.isEmpty())
+ {
+ promise.fail(new HttpException(HttpResponseStatus.INTERNAL_SERVER_ERROR.code(),
+ "Failed to import from directories: " + failedDirectories));
+ }
+ else
+ {
+ promise.complete();
+ cleanup(options);
+ }
+ }
+ catch (Exception exception)
+ {
+ LOGGER.error("Failed to import SSTables with options={}", options, exception);
+ promise.fail(exception);
+ }
+ }
+ }
+ }
+
+ /**
+ * Removes the staging directory recursively after a successful import
+ *
+ * @param options import options
+ */
+ private void cleanup(ImportOptions options)
+ {
+ uploadPathBuilder.resolveStagingDirectory(options.host, options.uploadId)
+ .compose(uploadPathBuilder::isValidDirectory)
+ .compose(stagingDirectory -> vertx.fileSystem()
+ .deleteRecursive(stagingDirectory, true))
+ .onSuccess(v ->
+ LOGGER.debug("Successfully removed staging directory for uploadId={}, " +
+ "instance={}, options={}", options.uploadId, options.host, options))
+ .onFailure(cause ->
+ LOGGER.error("Failed to remove staging directory for uploadId={}, " +
+ "instance={}, options={}", options.uploadId, options.host, options,
+ cause));
+ }
+
+ /**
+ * A {@link ConcurrentLinkedQueue} that allows for locking the queue while operating on it. The queue
+ * must be unlocked once the operations are complete.
+ */
+ static class ImportQueue extends ConcurrentLinkedQueue<Pair<Promise<Void>, ImportOptions>>
+ {
+ private final AtomicBoolean isQueueInUse = new AtomicBoolean(false);
+
+ /**
+ * @return true if the queue was successfully locked, false otherwise
+ */
+ public boolean tryLock()
+ {
+ return isQueueInUse.compareAndSet(false, true);
+ }
+
+ /**
+ * Unlocks the queue
+ */
+ public void unlock()
+ {
+ isQueueInUse.set(false);
+ }
+
+ public boolean removeIf(Predicate<? super Pair<Promise<Void>, ImportOptions>> filter)
+ {
+ return super.removeIf(filter);
+ }
Review Comment:
Remove it?
--
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-sidecar] yifan-c commented on a diff in pull request #45: CEP-28: Implement Bulk API endpoints and introduce the Sidecar Client to Support Bulk Analytics
Posted by "yifan-c (via GitHub)" <gi...@apache.org>.
yifan-c commented on code in PR #45:
URL: https://github.com/apache/cassandra-sidecar/pull/45#discussion_r1192861006
##########
client/src/main/java/org/apache/cassandra/sidecar/client/exception/UnexpectedStatusCodeException.java:
##########
@@ -0,0 +1,53 @@
+/*
+ * 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.sidecar.client.exception;
+
+/**
+ * Represents an exception raised when an unexpected status code is encountered
+ */
+public class UnexpectedStatusCodeException extends RuntimeException
+{
+ /**
+ * Constructs a new {@link UnexpectedStatusCodeException} with the given {@code statusCode} and {@code body}
+ *
+ * @param statusCode the response status code
+ * @param body the body of the response
+ */
+ public UnexpectedStatusCodeException(int statusCode, String body)
Review Comment:
Is it safe to assume the body is always `String`?
##########
client/src/main/java/org/apache/cassandra/sidecar/client/selection/OrderedInstanceSelectionPolicy.java:
##########
@@ -0,0 +1,54 @@
+/*
+ * 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.sidecar.client.selection;
+
+import java.util.Iterator;
+
+import org.apache.cassandra.sidecar.client.SidecarInstance;
+import org.apache.cassandra.sidecar.client.SidecarInstancesProvider;
+import org.jetbrains.annotations.NotNull;
+
+/**
+ * A selection policy for a multiple Cassandra Sidecar instances where the iterator returns in order
+ */
+public class OrderedInstanceSelectionPolicy implements InstanceSelectionPolicy
+{
+ protected final SidecarInstancesProvider instancesProvider;
+
+ /**
+ * Constructs a new {@link OrderedInstanceSelectionPolicy} with the provided list of instances
+ *
+ * @param instancesProvider the class that provides the sidecar instances
+ */
+ public OrderedInstanceSelectionPolicy(SidecarInstancesProvider instancesProvider)
+ {
+ this.instancesProvider = instancesProvider;
+ }
+
+ /**
+ * Returns an iterator of {@link SidecarInstance instances}.
+ *
+ * @return an iterator of {@link SidecarInstance instances}
+ */
+ @NotNull
+ public Iterator<SidecarInstance> iterator()
+ {
+ return instancesProvider.instances().iterator();
Review Comment:
The order depends in the value returned from `instancesProvider.instances()`, which is implementation dependent. For example, the provider could shuffle the instances and return. In this example, the `OrderedInstanceSelectionPolicy` is no different from `RandomInstanceSelectionPolicy`.
nit: It might want to sort the instances, so the order is guaranteed.
##########
client/src/main/java/org/apache/cassandra/sidecar/client/retry/ExponentialBackoffRetryPolicy.java:
##########
@@ -0,0 +1,90 @@
+/*
+ * 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.sidecar.client.retry;
+
+/**
+ * A retry policy that will perform an exponential backoff. The backoff period increases for each retry attempt.
+ *
+ * <p>Example: For a configured {@code maxRetries} of {@code 10}, {@code retryDelayMillis} of {@code 200}
+ * milliseconds, and {@code maxRetryDelayMillis} of {@code 20,000} milliseconds, the sequence is as follows:
+ *
+ * <pre>
+ * request backoff
+ *
+ * 1 200
+ * 2 400
+ * 3 800
+ * 4 1600
+ * 5 3200
+ * 6 6400
+ * 7 12800
+ * 8 20000
+ * 9 20000
+ * 10 20000
+ * </pre>
+ */
+public class ExponentialBackoffRetryPolicy extends BasicRetryPolicy
+{
+ private final long maxRetryDelayMillis;
+
+ /**
+ * Constructs an exponential backoff retry policy unlimited number of retries and no delay between retries.
+ */
+ public ExponentialBackoffRetryPolicy()
+ {
+ super();
+ this.maxRetryDelayMillis = 0;
+ }
+
+ /**
+ * Constructs an exponential backoff retry policy with {@code maxRetries} number of retries,
+ * {@code retryDelayMillis} delay between retries, and {@code maxRetryDelayMillis} maximum delay for the
+ * exponential backoff.
+ *
+ * @param maxRetries the maximum number of retries
+ * @param retryDelayMillis the delay between retries in milliseconds
+ * @param maxRetryDelayMillis the maximum retry delay in milliseconds
+ */
+ public ExponentialBackoffRetryPolicy(int maxRetries, long retryDelayMillis, long maxRetryDelayMillis)
+ {
+ super(maxRetries, retryDelayMillis);
+ this.maxRetryDelayMillis = maxRetryDelayMillis;
+ }
+
+ /**
+ * Returns the number of milliseconds to wait before attempting the next request. This value is upper-bounded
+ * by {@code maxRetryDelayMillis} if configured. The delay increases exponentially based on the number of
+ * attempts already performed.
+ *
+ * @param attempts the number of attempts already performed for this request
+ * @return the number of milliseconds to wait before attempting the next request
+ */
+ @Override
+ protected long retryDelayMillis(int attempts)
+ {
+ long exponentialValue = (long) Math.pow(2, attempts - 1);
+ // do not multiply times retryDelayMillis, if we've reached the Long.MAX_VALUE already to avoid overflows
+ long retryDelay = exponentialValue == Long.MAX_VALUE ? exponentialValue : exponentialValue * retryDelayMillis;
Review Comment:
`exponentialValue * retryDelayMillis` could overflow and result in a negative value.
But it will never happen in practice, no human could possibly wait for this long time.
##########
client/src/main/java/org/apache/cassandra/sidecar/client/request/Request.java:
##########
@@ -0,0 +1,95 @@
+/*
+ * 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.sidecar.client.request;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+
+import io.netty.handler.codec.http.HttpHeaderNames;
+import io.netty.handler.codec.http.HttpMethod;
+import org.apache.cassandra.sidecar.common.utils.HttpRange;
+
+/**
+ * An abstract class representing a request for Sidecar
+ */
+public abstract class Request
+{
+ protected final String requestURI;
+
+ /**
+ * Constructs a Sidecar request with the given {@code requestURI}. Defaults to {@code ssl} enabled.
+ *
+ * @param requestURI the URI of the request
+ */
+ protected Request(String requestURI)
+ {
+ this.requestURI = requestURI;
+ }
+
+ /**
+ * @return a map of headers for the request
+ */
+ public Map<String, String> headers()
+ {
+ HttpRange range = range();
+ if (range == null)
+ {
+ return Collections.emptyMap();
+ }
+ Map<String, String> headers = new HashMap<>();
+ headers.put(HttpHeaderNames.RANGE.toString(), range.toString());
+ return Collections.unmodifiableMap(headers);
+ }
+
+ /**
+ * @return the range for the HTTP request
+ */
+ protected HttpRange range()
+ {
+ return null;
+ }
+
+ /**
+ * @return the HTTP method to be used for the request
+ */
+ public HttpMethod method()
+ {
+ return HttpMethod.GET;
Review Comment:
nit: it would read more clear to not supply a default HttpMethod, and enforce the subclasses to define it.
##########
client/src/main/java/org/apache/cassandra/sidecar/client/retry/BasicRetryPolicy.java:
##########
@@ -0,0 +1,297 @@
+/*
+ * 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.sidecar.client.retry;
+
+import java.util.List;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.TimeUnit;
+
+import io.netty.handler.codec.http.HttpResponseStatus;
+import io.netty.handler.codec.http.HttpStatusClass;
+import org.apache.cassandra.sidecar.client.HttpResponse;
+import org.apache.cassandra.sidecar.client.exception.ResourceNotFoundException;
+import org.apache.cassandra.sidecar.client.request.Request;
+
+/**
+ * A basic {@link RetryPolicy} supporting standard status codes
+ */
+public class BasicRetryPolicy extends RetryPolicy
+{
+ protected static final String RETRY_AFTER = "Retry-After";
+ // Use -1 to retry indefinitely
Review Comment:
nit: define a constants
--
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-sidecar] frankgh closed pull request #45: CEP-28: Implement Bulk API endpoints and introduce the Sidecar Client to Support Bulk Analytics
Posted by "frankgh (via GitHub)" <gi...@apache.org>.
frankgh closed pull request #45: CEP-28: Implement Bulk API endpoints and introduce the Sidecar Client to Support Bulk Analytics
URL: https://github.com/apache/cassandra-sidecar/pull/45
--
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-sidecar] dineshjoshi commented on a diff in pull request #45: CEP-28: Implement Bulk API endpoints and introduce the Sidecar Client to Support Bulk Analytics
Posted by "dineshjoshi (via GitHub)" <gi...@apache.org>.
dineshjoshi commented on code in PR #45:
URL: https://github.com/apache/cassandra-sidecar/pull/45#discussion_r1191671509
##########
vertx-client/src/test/resources/log4j2.xml:
##########
@@ -0,0 +1,24 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<Configuration status="ERROR">
+ <Properties>
+ <Property name="LOG_PATTERN">%d{yyyy-MM-dd'T'HH:mm:ss.SSSZ} %p %m%n</Property>
+ <Property name="APP_LOG_ROOT">c:/temp</Property>
Review Comment:
c:/temp?
##########
src/test/resources/sidecar_with_single_multiple_instances.yaml:
##########
@@ -38,6 +38,8 @@ sidecar:
- stream_requests_per_sec: 5000
- delay_sec: 5
- timeout_sec: 10
+ - allowable_time_skew_in_minutes: 60
Review Comment:
Is 60 minutes a reasonable default?
##########
cassandra40/src/main/java/org/apache/cassandra/sidecar/cassandra40/TokenRangeReplicas.java:
##########
@@ -0,0 +1,417 @@
+/*
+ * 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.sidecar.cassandra40;
+
+import java.math.BigInteger;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Set;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import com.google.common.base.Objects;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.jetbrains.annotations.NotNull;
+
+
+/**
+ * Representation of a token range and the corresponding mapping to replica-set hosts
+ */
+public class TokenRangeReplicas implements Comparable<TokenRangeReplicas>
+{
+ private final BigInteger start;
+ private final BigInteger end;
+
+ private final Partitioner partitioner;
+
+ private final Set<String> replicaSet;
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(TokenRangeReplicas.class);
+
+ public TokenRangeReplicas(BigInteger start, BigInteger end, Partitioner partitioner, Set<String> replicaSet)
+ {
+ this.start = start;
+ this.end = end;
+ this.partitioner = partitioner;
+ this.replicaSet = replicaSet;
+ }
+
+
+ public BigInteger start()
+ {
+ return start;
+ }
+
+ public BigInteger end()
+ {
+ return end;
+ }
+
+ public Set<String> replicaSet()
+ {
+ return replicaSet;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public int compareTo(@NotNull TokenRangeReplicas other)
+ {
+ if (this.partitioner != other.partitioner)
+ throw new IllegalStateException("Token ranges being compared do not have the same partitioner");
+
+ // TODO
+ BigInteger maxValue = this.partitioner.maxToken;
+ if (this.start.compareTo(other.start) == 0)
+ {
+ if (this.end.equals(maxValue)) return 1;
+ else if (other.end.equals(maxValue)) return -1;
+ else return this.end.compareTo(other.end);
+ }
+ else return this.start.compareTo(other.start);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public boolean equals(Object o)
+ {
+ if (!(o instanceof TokenRangeReplicas))
+ {
+ return false;
+ }
+ TokenRangeReplicas that = (TokenRangeReplicas) o;
+ return (this.start.equals(that.start) && this.end.equals(that.end) && this.partitioner == that.partitioner);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public int hashCode()
+ {
+ return Objects.hashCode(start, end, partitioner);
+ }
+
+ private boolean isWrapAround()
+ {
+ return start.compareTo(end) >= 0;
+ }
+
+ private boolean isSubsetOf(TokenRangeReplicas other)
+ {
+ if (this.partitioner != other.partitioner)
+ throw new IllegalStateException("Token ranges being compared do not have the same partitioner");
+
+ BigInteger maxValue = this.partitioner.maxToken;
+ if (this.start.compareTo(other.start) >= 0)
+ {
+ // TODO:
Review Comment:
TODO?
##########
src/test/java/org/apache/cassandra/sidecar/routes/sstableuploads/BaseUploadsHandlerTest.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.sidecar.routes.sstableuploads;
+
+import java.io.File;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.UUID;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.stream.Stream;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.io.TempDir;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.datastax.driver.core.KeyspaceMetadata;
+import com.datastax.driver.core.Metadata;
+import com.datastax.driver.core.TableMetadata;
+import com.google.inject.AbstractModule;
+import com.google.inject.Guice;
+import com.google.inject.Injector;
+import com.google.inject.Provides;
+import com.google.inject.Singleton;
+import com.google.inject.util.Modules;
+import io.vertx.core.Vertx;
+import io.vertx.core.http.HttpServer;
+import io.vertx.ext.web.client.WebClient;
+import io.vertx.junit5.VertxTestContext;
+import org.apache.cassandra.sidecar.Configuration;
+import org.apache.cassandra.sidecar.MainModule;
+import org.apache.cassandra.sidecar.TestModule;
+import org.apache.cassandra.sidecar.cluster.InstancesConfig;
+import org.apache.cassandra.sidecar.common.CassandraAdapterDelegate;
+import org.apache.cassandra.sidecar.config.CacheConfiguration;
+import org.apache.cassandra.sidecar.config.WorkerPoolConfiguration;
+import org.apache.cassandra.sidecar.snapshots.SnapshotUtils;
+
+import static org.apache.cassandra.sidecar.snapshots.SnapshotUtils.mockInstancesConfig;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+/**
+ * Common functionality for the SSTable Uploads {@link SSTableUploadHandler}, {@link SSTableImportHandler},
+ * and {@link SSTableCleanupHandler} tests.
+ */
+class BaseUploadsHandlerTest
+{
+ protected final Logger logger = LoggerFactory.getLogger(this.getClass());
Review Comment:
logger -> LOGGER
--
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-sidecar] yifan-c commented on a diff in pull request #45: CEP-28: Implement Bulk API endpoints and introduce the Sidecar Client to Support Bulk Analytics
Posted by "yifan-c (via GitHub)" <gi...@apache.org>.
yifan-c commented on code in PR #45:
URL: https://github.com/apache/cassandra-sidecar/pull/45#discussion_r1192824961
##########
cassandra40/src/main/java/org/apache/cassandra/sidecar/cassandra40/TokenRangeReplicas.java:
##########
@@ -0,0 +1,417 @@
+/*
+ * 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.sidecar.cassandra40;
+
+import java.math.BigInteger;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Set;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import com.google.common.base.Objects;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.jetbrains.annotations.NotNull;
+
+
+/**
+ * Representation of a token range and the corresponding mapping to replica-set hosts
+ */
+public class TokenRangeReplicas implements Comparable<TokenRangeReplicas>
+{
+ private final BigInteger start;
+ private final BigInteger end;
+
+ private final Partitioner partitioner;
+
+ private final Set<String> replicaSet;
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(TokenRangeReplicas.class);
+
+ public TokenRangeReplicas(BigInteger start, BigInteger end, Partitioner partitioner, Set<String> replicaSet)
+ {
+ this.start = start;
+ this.end = end;
+ this.partitioner = partitioner;
+ this.replicaSet = replicaSet;
+ }
+
+
+ public BigInteger start()
+ {
+ return start;
+ }
+
+ public BigInteger end()
+ {
+ return end;
+ }
+
+ public Set<String> replicaSet()
+ {
+ return replicaSet;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public int compareTo(@NotNull TokenRangeReplicas other)
+ {
+ if (this.partitioner != other.partitioner)
+ throw new IllegalStateException("Token ranges being compared do not have the same partitioner");
+
+ // TODO
+ BigInteger maxValue = this.partitioner.maxToken;
+ if (this.start.compareTo(other.start) == 0)
+ {
+ if (this.end.equals(maxValue)) return 1;
+ else if (other.end.equals(maxValue)) return -1;
+ else return this.end.compareTo(other.end);
+ }
+ else return this.start.compareTo(other.start);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public boolean equals(Object o)
+ {
+ if (!(o instanceof TokenRangeReplicas))
+ {
+ return false;
+ }
+ TokenRangeReplicas that = (TokenRangeReplicas) o;
+ return (this.start.equals(that.start) && this.end.equals(that.end) && this.partitioner == that.partitioner);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public int hashCode()
+ {
+ return Objects.hashCode(start, end, partitioner);
+ }
+
+ private boolean isWrapAround()
+ {
+ return start.compareTo(end) >= 0;
+ }
+
+ private boolean isSubsetOf(TokenRangeReplicas other)
+ {
+ if (this.partitioner != other.partitioner)
+ throw new IllegalStateException("Token ranges being compared do not have the same partitioner");
+
+ BigInteger maxValue = this.partitioner.maxToken;
+ if (this.start.compareTo(other.start) >= 0)
+ {
+ // TODO:
+ if (other.end.equals(maxValue)) return true;
+ if (this.end.equals(maxValue)) return false;
+ if (this.end.compareTo(other.end) <= 0) return true;
+ }
+ return false;
+ }
+
+ /**
+ * For subset ranges, this is used to determine if a range is larger than the other by comparing start-end lengths
+ * If both ranges end at the min, we compare starting points to determine the result.
+ * When the left range is the only one ending at min, it is always the larger one since all subsequent ranges
+ * in the sorted range list have to be smaller.
+ *
+ * @param other the next range in the range list to compare
+ * @return true if "this" range is larger than the other
+ */
+ private boolean isLarger(TokenRangeReplicas other)
+ {
+ if (this.partitioner != other.partitioner)
+ throw new IllegalStateException("Token ranges being compared do not have the same partitioner");
+
+ // If both ranges end at min, we compare start of ranges
+ if (this.end.equals(partitioner.maxToken) && other.end.equals(partitioner.maxToken))
+ {
+ return this.start.compareTo(other.start) < 0;
+ }
+
+ if (this.end.equals(partitioner.maxToken)) return true;
+ if (other.end.equals(partitioner.maxToken)) return false;
+
+ return this.end.subtract(this.start).compareTo(other.end.subtract(other.start)) > 0;
+ }
+
+ /**
+ * Determines intersection if the next range starts before the current range ends.
+ * When the current range ending at min, we determine intersection merely if the next range starts after the current
+ * since all subsequent ranges have to be subsets.
+ *
+ * @param other the range we are currently processing to check if "this" intersects it
+ * @return true if "this" range intersects the other
+ */
+ private boolean intersects(TokenRangeReplicas other)
+ {
+ return (other.end.compareTo(partitioner.maxToken) == 0 && this.start.compareTo(other.start) > 0) ||
+ this.start.compareTo(other.end) < 0;
+ }
Review Comment:
I think this implementation is wrong. You want to compare `this.end.compareTo(other.start) < 0;`. Before the comparison, it needs to sort the 2 ranges by `start`, and make sure to compare left range with right range.
~Beside that, the first condition that checks with the maxToken of the partitioner seems not necessary. It only wants to compare 2 ranges.~
(Edit: looks like wrap around is considered. In that case, either this or that range needs to unwrap to check intersection.)
The below test fails
```java
@Test
void testInterests()
{
TokenRangeReplicas range1 = new TokenRangeReplicas(BigInteger.valueOf(1), BigInteger.valueOf(10), Partitioner.Murmur3, new HashSet<>());
TokenRangeReplicas range2 = new TokenRangeReplicas(BigInteger.valueOf(9), BigInteger.valueOf(12), Partitioner.Murmur3, new HashSet<>());
assertThat(range1.intersects(range2)).isTrue();
assertThat(range2.intersects(range1)).isTrue();
TokenRangeReplicas range3 = new TokenRangeReplicas(BigInteger.valueOf(1), BigInteger.valueOf(10), Partitioner.Murmur3, new HashSet<>());
TokenRangeReplicas range4 = new TokenRangeReplicas(BigInteger.valueOf(11), BigInteger.valueOf(20), Partitioner.Murmur3, new HashSet<>());
assertThat(range3.intersects(range4)).isFalse();
assertThat(range4.intersects(range3)).isFalse();
}
```
--
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-sidecar] frankgh commented on a diff in pull request #45: CEP-28: Implement Bulk API endpoints and introduce the Sidecar Client to Support Bulk Analytics
Posted by "frankgh (via GitHub)" <gi...@apache.org>.
frankgh commented on code in PR #45:
URL: https://github.com/apache/cassandra-sidecar/pull/45#discussion_r1192872529
##########
client/src/main/java/org/apache/cassandra/sidecar/client/retry/ExponentialBackoffRetryPolicy.java:
##########
@@ -0,0 +1,90 @@
+/*
+ * 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.sidecar.client.retry;
+
+/**
+ * A retry policy that will perform an exponential backoff. The backoff period increases for each retry attempt.
+ *
+ * <p>Example: For a configured {@code maxRetries} of {@code 10}, {@code retryDelayMillis} of {@code 200}
+ * milliseconds, and {@code maxRetryDelayMillis} of {@code 20,000} milliseconds, the sequence is as follows:
+ *
+ * <pre>
+ * request backoff
+ *
+ * 1 200
+ * 2 400
+ * 3 800
+ * 4 1600
+ * 5 3200
+ * 6 6400
+ * 7 12800
+ * 8 20000
+ * 9 20000
+ * 10 20000
+ * </pre>
+ */
+public class ExponentialBackoffRetryPolicy extends BasicRetryPolicy
+{
+ private final long maxRetryDelayMillis;
+
+ /**
+ * Constructs an exponential backoff retry policy unlimited number of retries and no delay between retries.
+ */
+ public ExponentialBackoffRetryPolicy()
+ {
+ super();
+ this.maxRetryDelayMillis = 0;
+ }
+
+ /**
+ * Constructs an exponential backoff retry policy with {@code maxRetries} number of retries,
+ * {@code retryDelayMillis} delay between retries, and {@code maxRetryDelayMillis} maximum delay for the
+ * exponential backoff.
+ *
+ * @param maxRetries the maximum number of retries
+ * @param retryDelayMillis the delay between retries in milliseconds
+ * @param maxRetryDelayMillis the maximum retry delay in milliseconds
+ */
+ public ExponentialBackoffRetryPolicy(int maxRetries, long retryDelayMillis, long maxRetryDelayMillis)
+ {
+ super(maxRetries, retryDelayMillis);
+ this.maxRetryDelayMillis = maxRetryDelayMillis;
+ }
+
+ /**
+ * Returns the number of milliseconds to wait before attempting the next request. This value is upper-bounded
+ * by {@code maxRetryDelayMillis} if configured. The delay increases exponentially based on the number of
+ * attempts already performed.
+ *
+ * @param attempts the number of attempts already performed for this request
+ * @return the number of milliseconds to wait before attempting the next request
+ */
+ @Override
+ protected long retryDelayMillis(int attempts)
+ {
+ long exponentialValue = (long) Math.pow(2, attempts - 1);
+ // do not multiply times retryDelayMillis, if we've reached the Long.MAX_VALUE already to avoid overflows
+ long retryDelay = exponentialValue == Long.MAX_VALUE ? exponentialValue : exponentialValue * retryDelayMillis;
Review Comment:
this check here is so it doesn't overflow. Math.pow will return Long.MAX_VALUE if it will overflow.
--
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-sidecar] yifan-c commented on a diff in pull request #45: CEP-28: Implement Bulk API endpoints and introduce the Sidecar Client to Support Bulk Analytics
Posted by "yifan-c (via GitHub)" <gi...@apache.org>.
yifan-c commented on code in PR #45:
URL: https://github.com/apache/cassandra-sidecar/pull/45#discussion_r1192870200
##########
cassandra40/build.gradle:
##########
@@ -12,7 +13,34 @@ repositories {
mavenCentral()
}
+test {
+ useJUnitPlatform()
+}
+
dependencies {
- compile project(":common")
- implementation('org.jetbrains:annotations:23.0.0')
+ implementation(project(":common"))
+ compileOnly('org.jetbrains:annotations:23.0.0')
+ compileOnly('com.datastax.cassandra:cassandra-driver-core:3.11.3')
+ implementation("com.google.guava:guava:${project.rootProject.guavaVersion}")
+ implementation("org.slf4j:slf4j-api:${project.slf4jVersion}")
+
+ testImplementation "org.junit.jupiter:junit-jupiter-api:${project.junitVersion}"
+ testImplementation "org.junit.jupiter:junit-jupiter-params:${project.junitVersion}"
+ testImplementation "org.assertj:assertj-core:3.24.2"
+ testRuntimeOnly "org.junit.jupiter:junit-jupiter-engine:${project.junitVersion}"
+
+ testImplementation('org.mockito:mockito-core:4.10.0')
+ testImplementation('org.mockito:mockito-inline:4.10.0')
+
+}
+
+publishing {
Review Comment:
As said, feel free to ignore the nits.
--
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-sidecar] frankgh commented on a diff in pull request #45: CEP-28: Implement Bulk API endpoints and introduce the Sidecar Client to Support Bulk Analytics
Posted by "frankgh (via GitHub)" <gi...@apache.org>.
frankgh commented on code in PR #45:
URL: https://github.com/apache/cassandra-sidecar/pull/45#discussion_r1194174015
##########
cassandra40/src/main/java/org/apache/cassandra/sidecar/cassandra40/TokenRangeReplicas.java:
##########
@@ -0,0 +1,417 @@
+/*
+ * 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.sidecar.cassandra40;
+
+import java.math.BigInteger;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Set;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import com.google.common.base.Objects;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.jetbrains.annotations.NotNull;
+
+
+/**
+ * Representation of a token range and the corresponding mapping to replica-set hosts
+ */
+public class TokenRangeReplicas implements Comparable<TokenRangeReplicas>
+{
+ private final BigInteger start;
+ private final BigInteger end;
+
+ private final Partitioner partitioner;
+
+ private final Set<String> replicaSet;
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(TokenRangeReplicas.class);
+
+ public TokenRangeReplicas(BigInteger start, BigInteger end, Partitioner partitioner, Set<String> replicaSet)
+ {
+ this.start = start;
+ this.end = end;
+ this.partitioner = partitioner;
+ this.replicaSet = replicaSet;
+ }
+
+
+ public BigInteger start()
+ {
+ return start;
+ }
+
+ public BigInteger end()
+ {
+ return end;
+ }
+
+ public Set<String> replicaSet()
+ {
+ return replicaSet;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public int compareTo(@NotNull TokenRangeReplicas other)
+ {
+ if (this.partitioner != other.partitioner)
+ throw new IllegalStateException("Token ranges being compared do not have the same partitioner");
+
+ // TODO
+ BigInteger maxValue = this.partitioner.maxToken;
+ if (this.start.compareTo(other.start) == 0)
+ {
+ if (this.end.equals(maxValue)) return 1;
+ else if (other.end.equals(maxValue)) return -1;
+ else return this.end.compareTo(other.end);
+ }
+ else return this.start.compareTo(other.start);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public boolean equals(Object o)
+ {
+ if (!(o instanceof TokenRangeReplicas))
+ {
+ return false;
+ }
+ TokenRangeReplicas that = (TokenRangeReplicas) o;
+ return (this.start.equals(that.start) && this.end.equals(that.end) && this.partitioner == that.partitioner);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public int hashCode()
+ {
+ return Objects.hashCode(start, end, partitioner);
+ }
+
+ private boolean isWrapAround()
+ {
+ return start.compareTo(end) >= 0;
+ }
+
+ private boolean isSubsetOf(TokenRangeReplicas other)
+ {
+ if (this.partitioner != other.partitioner)
+ throw new IllegalStateException("Token ranges being compared do not have the same partitioner");
+
+ BigInteger maxValue = this.partitioner.maxToken;
+ if (this.start.compareTo(other.start) >= 0)
+ {
+ // TODO:
+ if (other.end.equals(maxValue)) return true;
+ if (this.end.equals(maxValue)) return false;
+ if (this.end.compareTo(other.end) <= 0) return true;
+ }
+ return false;
+ }
+
+ /**
+ * For subset ranges, this is used to determine if a range is larger than the other by comparing start-end lengths
+ * If both ranges end at the min, we compare starting points to determine the result.
+ * When the left range is the only one ending at min, it is always the larger one since all subsequent ranges
+ * in the sorted range list have to be smaller.
+ *
+ * @param other the next range in the range list to compare
+ * @return true if "this" range is larger than the other
+ */
+ private boolean isLarger(TokenRangeReplicas other)
+ {
+ if (this.partitioner != other.partitioner)
+ throw new IllegalStateException("Token ranges being compared do not have the same partitioner");
+
+ // If both ranges end at min, we compare start of ranges
+ if (this.end.equals(partitioner.maxToken) && other.end.equals(partitioner.maxToken))
+ {
+ return this.start.compareTo(other.start) < 0;
+ }
+
+ if (this.end.equals(partitioner.maxToken)) return true;
+ if (other.end.equals(partitioner.maxToken)) return false;
+
+ return this.end.subtract(this.start).compareTo(other.end.subtract(other.start)) > 0;
+ }
+
+ /**
+ * Determines intersection if the next range starts before the current range ends.
+ * When the current range ending at min, we determine intersection merely if the next range starts after the current
+ * since all subsequent ranges have to be subsets.
+ *
+ * @param other the range we are currently processing to check if "this" intersects it
+ * @return true if "this" range intersects the other
+ */
+ private boolean intersects(TokenRangeReplicas other)
+ {
+ return (other.end.compareTo(partitioner.maxToken) == 0 && this.start.compareTo(other.start) > 0) ||
+ this.start.compareTo(other.end) < 0;
+ }
Review Comment:
Adding this test and providing a fixed implementation
--
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-sidecar] frankgh commented on a diff in pull request #45: CEP-28: Implement Bulk API endpoints and introduce the Sidecar Client to Support Bulk Analytics
Posted by "frankgh (via GitHub)" <gi...@apache.org>.
frankgh commented on code in PR #45:
URL: https://github.com/apache/cassandra-sidecar/pull/45#discussion_r1194342932
##########
client/src/testFixtures/java/org/apache/cassandra/sidecar/client/request/GossipInfoRequestTestParameters.java:
##########
@@ -0,0 +1,72 @@
+/*
+ * 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.sidecar.client.request;
+
+import org.apache.cassandra.sidecar.client.RequestContext;
+import org.apache.cassandra.sidecar.common.ApiEndpointsV1;
+import org.apache.cassandra.sidecar.common.data.GossipInfoResponse;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+/**
+ * Unit tests for client requests accessing the gossip info endpoint
+ */
+public class GossipInfoRequestTestParameters implements RequestTestParameters<GossipInfoResponse>
+{
+ @Override
+ public RequestContext.Builder specificRequest(RequestContext.Builder requestContextBuilder)
+ {
+ return requestContextBuilder.gossipInfoRequest();
+ }
+
+ @Override
+ public String okResponseBody()
+ {
+ return "{\"/127.0.0.3:7000\":{\"generation\":\"1679961466\"," +
+ "\"schema\":\"4994b214-7a05-35ea-a11c-d092a554dd5d\",\"rack\":\"101000301\"," +
+ "\"heartbeat\":\"2114\",\"releaseVersion\":\"4.0.8\"," +
+ "\"hostId\":\"be19c254-becb-40b9-8951-30c589c7028e\",\"nativeAddressAndPort\":\"127.0.0.3:9042\"," +
+ "\"load\":\"89083.0\",\"sstableVersions\":\"big-nb\",\"tokens\":\"<hidden>\",\"rpcReady\":\"true\"," +
+ "\"dc\":\"LO\",\"netVersion\":\"12\",\"statusWithPort\":\"NORMAL,3074457345618258602\"}," +
+ "\"/127.0.0.1:7000\":{\"generation\":\"1679961466\"," +
+ "\"schema\":\"4994b214-7a05-35ea-a11c-d092a554dd5d\",\"rack\":\"101000101\",\"heartbeat\":\"2108\"," +
+ "\"releaseVersion\":\"4.0.8\",\"rpcAddress\":\"172.17.0.2\"," +
+ "\"hostId\":\"33cae238-8203-41c1-880f-8cdf98ee6720\",\"nativeAddressAndPort\":\"172.17.0.2:9042\"," +
+ "\"load\":\"89082.0\",\"sstableVersions\":\"big-nb\",\"tokens\":\"<hidden>\",\"rpcReady\":\"true\"," +
+ "\"status\":\"NORMAL,-9223372036854775808\",\"dc\":\"LO\",\"netVersion\":\"12\",\"statusWithPort\":" +
+ "\"NORMAL,-9223372036854775808\"},\"/127.0.0.2:7000\":{\"generation\":\"1679961465\"," +
+ "\"schema\":\"4994b214-7a05-35ea-a11c-d092a554dd5d\",\"rack\":\"101000201\",\"heartbeat\":\"2108\"," +
+ "\"releaseVersion\":\"4.0.8\",\"hostId\":\"dba02656-ea8c-4a1d-8011-cbc0dab5f411\"," +
+ "\"nativeAddressAndPort\":\"127.0.0.2:9042\",\"load\":\"89084.0\",\"sstableVersions\":\"big-nb\"," +
+ "\"tokens\":\"<hidden>\",\"rpcReady\":\"true\",\"dc\":\"LO\",\"netVersion\":\"12\"," +
+ "\"statusWithPort\":\"NORMAL,-3074457345618258603\"}}[root@b77ac3582e25 /]";
Review Comment:
removed the added string, but I agree with you about making the test prep more robust
--
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-sidecar] frankgh commented on a diff in pull request #45: CEP-28: Implement Bulk API endpoints and introduce the Sidecar Client to Support Bulk Analytics
Posted by "frankgh (via GitHub)" <gi...@apache.org>.
frankgh commented on code in PR #45:
URL: https://github.com/apache/cassandra-sidecar/pull/45#discussion_r1194175536
##########
client/src/main/java/org/apache/cassandra/sidecar/client/retry/ExponentialBackoffRetryPolicy.java:
##########
@@ -0,0 +1,90 @@
+/*
+ * 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.sidecar.client.retry;
+
+/**
+ * A retry policy that will perform an exponential backoff. The backoff period increases for each retry attempt.
+ *
+ * <p>Example: For a configured {@code maxRetries} of {@code 10}, {@code retryDelayMillis} of {@code 200}
+ * milliseconds, and {@code maxRetryDelayMillis} of {@code 20,000} milliseconds, the sequence is as follows:
+ *
+ * <pre>
+ * request backoff
+ *
+ * 1 200
+ * 2 400
+ * 3 800
+ * 4 1600
+ * 5 3200
+ * 6 6400
+ * 7 12800
+ * 8 20000
+ * 9 20000
+ * 10 20000
+ * </pre>
+ */
+public class ExponentialBackoffRetryPolicy extends BasicRetryPolicy
+{
+ private final long maxRetryDelayMillis;
+
+ /**
+ * Constructs an exponential backoff retry policy unlimited number of retries and no delay between retries.
+ */
+ public ExponentialBackoffRetryPolicy()
+ {
+ super();
+ this.maxRetryDelayMillis = 0;
+ }
+
+ /**
+ * Constructs an exponential backoff retry policy with {@code maxRetries} number of retries,
+ * {@code retryDelayMillis} delay between retries, and {@code maxRetryDelayMillis} maximum delay for the
+ * exponential backoff.
+ *
+ * @param maxRetries the maximum number of retries
+ * @param retryDelayMillis the delay between retries in milliseconds
+ * @param maxRetryDelayMillis the maximum retry delay in milliseconds
+ */
+ public ExponentialBackoffRetryPolicy(int maxRetries, long retryDelayMillis, long maxRetryDelayMillis)
+ {
+ super(maxRetries, retryDelayMillis);
+ this.maxRetryDelayMillis = maxRetryDelayMillis;
+ }
+
+ /**
+ * Returns the number of milliseconds to wait before attempting the next request. This value is upper-bounded
+ * by {@code maxRetryDelayMillis} if configured. The delay increases exponentially based on the number of
+ * attempts already performed.
+ *
+ * @param attempts the number of attempts already performed for this request
+ * @return the number of milliseconds to wait before attempting the next request
+ */
+ @Override
+ protected long retryDelayMillis(int attempts)
+ {
+ long exponentialValue = (long) Math.pow(2, attempts - 1);
+ // do not multiply times retryDelayMillis, if we've reached the Long.MAX_VALUE already to avoid overflows
+ long retryDelay = exponentialValue == Long.MAX_VALUE ? exponentialValue : exponentialValue * retryDelayMillis;
Review Comment:
ah yeah, that will overflow for sure. I will make it more robust
--
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-sidecar] frankgh commented on a diff in pull request #45: CEP-28: Implement Bulk API endpoints and introduce the Sidecar Client to Support Bulk Analytics
Posted by "frankgh (via GitHub)" <gi...@apache.org>.
frankgh commented on code in PR #45:
URL: https://github.com/apache/cassandra-sidecar/pull/45#discussion_r1194412246
##########
client/src/main/java/org/apache/cassandra/sidecar/client/RequestContext.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.sidecar.client;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.apache.cassandra.sidecar.client.request.CleanSSTableUploadSessionRequest;
+import org.apache.cassandra.sidecar.client.request.ClearSnapshotRequest;
+import org.apache.cassandra.sidecar.client.request.CreateSnapshotRequest;
+import org.apache.cassandra.sidecar.client.request.GossipInfoRequest;
+import org.apache.cassandra.sidecar.client.request.ImportSSTableRequest;
+import org.apache.cassandra.sidecar.client.request.ListSnapshotFilesRequest;
+import org.apache.cassandra.sidecar.client.request.NodeSettingsRequest;
+import org.apache.cassandra.sidecar.client.request.Request;
+import org.apache.cassandra.sidecar.client.request.RingRequest;
+import org.apache.cassandra.sidecar.client.request.SSTableComponentRequest;
+import org.apache.cassandra.sidecar.client.request.SchemaRequest;
+import org.apache.cassandra.sidecar.client.request.TimeSkewRequest;
+import org.apache.cassandra.sidecar.client.request.TokenRangeReplicasRequest;
+import org.apache.cassandra.sidecar.client.request.UploadSSTableRequest;
+import org.apache.cassandra.sidecar.client.retry.ExponentialBackoffRetryPolicy;
+import org.apache.cassandra.sidecar.client.retry.NoRetryPolicy;
+import org.apache.cassandra.sidecar.client.retry.RetryPolicy;
+import org.apache.cassandra.sidecar.client.selection.InstanceSelectionPolicy;
+import org.apache.cassandra.sidecar.client.selection.SingleInstanceSelectionPolicy;
+import org.apache.cassandra.sidecar.common.utils.HttpRange;
+
+/**
+ * The context for a given request that include the {@link InstanceSelectionPolicy}, the {@link RetryPolicy}, and
+ * the {@link Request}
+ */
+public class RequestContext
+{
+ protected static final SchemaRequest FULL_SCHEMA_REQUEST = new SchemaRequest();
+ protected static final TimeSkewRequest TIME_SKEW_REQUEST = new TimeSkewRequest();
+ protected static final NodeSettingsRequest NODE_SETTINGS_REQUEST = new NodeSettingsRequest();
+ protected static final RingRequest RING_REQUEST = new RingRequest();
Review Comment:
maybe we can have it as a follow up
--
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-sidecar] frankgh commented on pull request #45: CEP-28: Implement Bulk API endpoints and introduce the Sidecar Client to Support Bulk Analytics
Posted by "frankgh (via GitHub)" <gi...@apache.org>.
frankgh commented on PR #45:
URL: https://github.com/apache/cassandra-sidecar/pull/45#issuecomment-1567178517
Closed via https://github.com/apache/cassandra-sidecar/commit/38cdacb2e7418e2aefbcffb1754dcd324c46028d
--
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-sidecar] frankgh commented on a diff in pull request #45: CEP-28: Implement Bulk API endpoints and introduce the Sidecar Client to Support Bulk Analytics
Posted by "frankgh (via GitHub)" <gi...@apache.org>.
frankgh commented on code in PR #45:
URL: https://github.com/apache/cassandra-sidecar/pull/45#discussion_r1194227438
##########
cassandra40/src/main/java/org/apache/cassandra/sidecar/cassandra40/TokenRangeReplicaProvider.java:
##########
@@ -0,0 +1,165 @@
+/*
+ * 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.sidecar.cassandra40;
+
+import java.math.BigInteger;
+import java.net.UnknownHostException;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.apache.cassandra.sidecar.common.JmxClient;
+import org.apache.cassandra.sidecar.common.data.TokenRangeReplicasResponse;
+import org.jetbrains.annotations.NotNull;
+
+import static org.apache.cassandra.sidecar.cassandra40.EndpointSnitchJmxOperations.ENDPOINT_SNITCH_INFO_OBJ_NAME;
+import static org.apache.cassandra.sidecar.cassandra40.StorageJmxOperations.STORAGE_SERVICE_OBJ_NAME;
+
+/**
+ * Aggregates the replica-set by token range
+ */
+public class TokenRangeReplicaProvider
+{
+ private final JmxClient jmxClient;
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(TokenRangeReplicaProvider.class);
+
+ public TokenRangeReplicaProvider(JmxClient jmxClient)
+ {
+ this.jmxClient = jmxClient;
+ }
+
+ public TokenRangeReplicasResponse tokenRangeReplicas(String keyspace, Partitioner partitioner)
+ {
+ Objects.requireNonNull(keyspace, "keyspace must be non-null");
+
+ StorageJmxOperations storage = jmxClient.proxy(StorageJmxOperations.class, STORAGE_SERVICE_OBJ_NAME);
+
+ // Retrieve map of primary token ranges to endpoints that describe the ring topology
+ Map<List<String>, List<String>> rangeToEndpointMappings = storage.getRangeToEndpointWithPortMap(keyspace);
+ // Pending ranges include bootstrap tokens and leaving endpoints as represented in the Cassandra TokenMetadata
+ Map<List<String>, List<String>> pendingRangeMappings = storage.getPendingRangeToEndpointWithPortMap(keyspace);
+
+ Stream<String> hostsStream = Stream.concat(rangeToEndpointMappings.values().stream().flatMap(List::stream),
+ pendingRangeMappings.values().stream().flatMap(List::stream));
+
+ Map<String, String> hostToDatacenter = groupHostsByDatacenter(hostsStream);
+
+ // Retrieve map of all token ranges (pending & primary) to endpoints
+ List<TokenRangeReplicasResponse.ReplicaInfo> writeReplicas =
+ writeReplicasFromPendingRanges(rangeToEndpointMappings,
+ pendingRangeMappings,
+ hostToDatacenter,
+ partitioner,
+ keyspace);
+
+ return new TokenRangeReplicasResponse(
+ writeReplicas,
+ mappingsToUnwrappedReplicaSet(rangeToEndpointMappings, hostToDatacenter, partitioner));
+ }
+
+ private List<TokenRangeReplicasResponse.ReplicaInfo>
+ writeReplicasFromPendingRanges(Map<List<String>, List<String>> readReplicaMappings,
Review Comment:
yeah, makes sense, it always felt odd to call it read replicas.
--
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-sidecar] frankgh commented on a diff in pull request #45: CEP-28: Implement Bulk API endpoints and introduce the Sidecar Client to Support Bulk Analytics
Posted by "frankgh (via GitHub)" <gi...@apache.org>.
frankgh commented on code in PR #45:
URL: https://github.com/apache/cassandra-sidecar/pull/45#discussion_r1194348922
##########
client/src/testFixtures/java/org/apache/cassandra/sidecar/client/request/GossipInfoRequestTestParameters.java:
##########
@@ -0,0 +1,72 @@
+/*
+ * 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.sidecar.client.request;
+
+import org.apache.cassandra.sidecar.client.RequestContext;
+import org.apache.cassandra.sidecar.common.ApiEndpointsV1;
+import org.apache.cassandra.sidecar.common.data.GossipInfoResponse;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+/**
+ * Unit tests for client requests accessing the gossip info endpoint
+ */
+public class GossipInfoRequestTestParameters implements RequestTestParameters<GossipInfoResponse>
+{
+ @Override
+ public RequestContext.Builder specificRequest(RequestContext.Builder requestContextBuilder)
+ {
+ return requestContextBuilder.gossipInfoRequest();
+ }
+
+ @Override
+ public String okResponseBody()
+ {
+ return "{\"/127.0.0.3:7000\":{\"generation\":\"1679961466\"," +
+ "\"schema\":\"4994b214-7a05-35ea-a11c-d092a554dd5d\",\"rack\":\"101000301\"," +
+ "\"heartbeat\":\"2114\",\"releaseVersion\":\"4.0.8\"," +
+ "\"hostId\":\"be19c254-becb-40b9-8951-30c589c7028e\",\"nativeAddressAndPort\":\"127.0.0.3:9042\"," +
+ "\"load\":\"89083.0\",\"sstableVersions\":\"big-nb\",\"tokens\":\"<hidden>\",\"rpcReady\":\"true\"," +
+ "\"dc\":\"LO\",\"netVersion\":\"12\",\"statusWithPort\":\"NORMAL,3074457345618258602\"}," +
+ "\"/127.0.0.1:7000\":{\"generation\":\"1679961466\"," +
+ "\"schema\":\"4994b214-7a05-35ea-a11c-d092a554dd5d\",\"rack\":\"101000101\",\"heartbeat\":\"2108\"," +
+ "\"releaseVersion\":\"4.0.8\",\"rpcAddress\":\"172.17.0.2\"," +
+ "\"hostId\":\"33cae238-8203-41c1-880f-8cdf98ee6720\",\"nativeAddressAndPort\":\"172.17.0.2:9042\"," +
+ "\"load\":\"89082.0\",\"sstableVersions\":\"big-nb\",\"tokens\":\"<hidden>\",\"rpcReady\":\"true\"," +
+ "\"status\":\"NORMAL,-9223372036854775808\",\"dc\":\"LO\",\"netVersion\":\"12\",\"statusWithPort\":" +
+ "\"NORMAL,-9223372036854775808\"},\"/127.0.0.2:7000\":{\"generation\":\"1679961465\"," +
+ "\"schema\":\"4994b214-7a05-35ea-a11c-d092a554dd5d\",\"rack\":\"101000201\",\"heartbeat\":\"2108\"," +
+ "\"releaseVersion\":\"4.0.8\",\"hostId\":\"dba02656-ea8c-4a1d-8011-cbc0dab5f411\"," +
+ "\"nativeAddressAndPort\":\"127.0.0.2:9042\",\"load\":\"89084.0\",\"sstableVersions\":\"big-nb\"," +
+ "\"tokens\":\"<hidden>\",\"rpcReady\":\"true\",\"dc\":\"LO\",\"netVersion\":\"12\"," +
+ "\"statusWithPort\":\"NORMAL,-3074457345618258603\"}}[root@b77ac3582e25 /]";
Review Comment:
for now, I will keep the clean string.
--
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-sidecar] frankgh commented on a diff in pull request #45: CEP-28: Implement Bulk API endpoints and introduce the Sidecar Client to Support Bulk Analytics
Posted by "frankgh (via GitHub)" <gi...@apache.org>.
frankgh commented on code in PR #45:
URL: https://github.com/apache/cassandra-sidecar/pull/45#discussion_r1194350552
##########
common/src/main/java/org/apache/cassandra/sidecar/common/CassandraAdapterDelegate.java:
##########
@@ -145,47 +124,73 @@ private void healthCheckInternal()
Row oneResult = activeSession.execute("select release_version, partitioner from system.local")
.one();
- String releaseVersion = oneResult.getString("release_version");
- // update the nodeSettings cache.
// Note that within the scope of this method, we should keep on using the local releaseVersion
- nodeSettings = new NodeSettings(releaseVersion, oneResult.getString("partitioner"));
- // this might swap the adapter out
- SimpleCassandraVersion newVersion = SimpleCassandraVersion.create(releaseVersion);
- if (!newVersion.equals(currentVersion))
+ String releaseVersion = oneResult.getString("release_version");
+ NodeSettings newNodeSettings = new NodeSettings(releaseVersion, oneResult.getString("partitioner"));
+ if (!newNodeSettings.equals(nodeSettings))
{
- currentVersion = newVersion;
- adapter = versionProvider.getCassandra(nodeSettings.releaseVersion()).create(cqlSession, jmxClient);
- logger.info("Cassandra version change detected. New adapter loaded: {}", adapter);
+ // update the nodeSettings cache.
+ SimpleCassandraVersion previousVersion = currentVersion;
+ currentVersion = SimpleCassandraVersion.create(releaseVersion);
+ adapter = versionProvider.cassandra(releaseVersion)
+ .create(cqlSessionProvider, jmxClient);
+ nodeSettings = newNodeSettings;
Review Comment:
this shouldn't be an issue because this method is guaranteed to only run by a single thread
--
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-sidecar] frankgh commented on a diff in pull request #45: CEP-28: Implement Bulk API endpoints and introduce the Sidecar Client to Support Bulk Analytics
Posted by "frankgh (via GitHub)" <gi...@apache.org>.
frankgh commented on code in PR #45:
URL: https://github.com/apache/cassandra-sidecar/pull/45#discussion_r1194293237
##########
client/src/test/java/org/apache/cassandra/sidecar/client/selection/RandomInstanceSelectionPolicyTest.java:
##########
@@ -0,0 +1,72 @@
+/*
+ * 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.sidecar.client.selection;
+
+import java.util.Arrays;
+import java.util.Iterator;
+import java.util.List;
+import java.util.NoSuchElementException;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import org.apache.cassandra.sidecar.client.SidecarInstance;
+import org.apache.cassandra.sidecar.client.SidecarInstancesProvider;
+import org.apache.cassandra.sidecar.client.SimpleSidecarInstancesProvider;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
+import static org.mockito.Mockito.mock;
+
+/**
+ * Unit tests for the {@link RandomInstanceSelectionPolicy}
+ */
+class RandomInstanceSelectionPolicyTest
+{
+ List<SidecarInstance> mockInstanceList;
+
+ @BeforeEach
+ void setup()
+ {
+ mockInstanceList = Arrays.asList(mock(SidecarInstance.class), mock(SidecarInstance.class),
+ mock(SidecarInstance.class), mock(SidecarInstance.class)
+ );
+ }
+
+ @Test
+ public void testIterator()
+ {
+ SidecarInstancesProvider provider = new SimpleSidecarInstancesProvider(mockInstanceList);
+ InstanceSelectionPolicy instanceSelectionPolicy = new RandomInstanceSelectionPolicy(provider);
+ Iterator<SidecarInstance> iterator = instanceSelectionPolicy.iterator();
+
+ assertThat(iterator.hasNext()).isTrue();
+ assertThat(iterator.hasNext()).isTrue().as("Expected to be true");
Review Comment:
testing idempotency of hasNext. I will add a comment to make it clear
##########
client/src/test/java/org/apache/cassandra/sidecar/client/selection/OrderedInstanceSelectionPolicyTest.java:
##########
@@ -0,0 +1,79 @@
+/*
+ * 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.sidecar.client.selection;
+
+import java.util.Arrays;
+import java.util.Iterator;
+import java.util.List;
+import java.util.NoSuchElementException;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import org.apache.cassandra.sidecar.client.SidecarInstance;
+import org.apache.cassandra.sidecar.client.SidecarInstancesProvider;
+import org.apache.cassandra.sidecar.client.SimpleSidecarInstancesProvider;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
+import static org.mockito.Mockito.mock;
+
+/**
+ * Unit tests for the {@link OrderedInstanceSelectionPolicy}
+ */
+class OrderedInstanceSelectionPolicyTest
+{
+ List<SidecarInstance> mockInstanceList;
+ SidecarInstance mockInstance1;
+ SidecarInstance mockInstance2;
+ SidecarInstance mockInstance3;
+ SidecarInstance mockInstance4;
+
+ @BeforeEach
+ void setup()
+ {
+ mockInstance1 = mock(SidecarInstance.class);
+ mockInstance2 = mock(SidecarInstance.class);
+ mockInstance3 = mock(SidecarInstance.class);
+ mockInstance4 = mock(SidecarInstance.class);
+ mockInstanceList = Arrays.asList(mockInstance1, mockInstance2, mockInstance3, mockInstance4);
+ }
+
+ @Test
+ public void testIterator()
+ {
+
+ SidecarInstancesProvider provider = new SimpleSidecarInstancesProvider(mockInstanceList);
+ InstanceSelectionPolicy instanceSelectionPolicy = new OrderedInstanceSelectionPolicy(provider);
+ Iterator<SidecarInstance> iterator = instanceSelectionPolicy.iterator();
+
+ assertThat(iterator.hasNext()).isTrue();
+ assertThat(iterator.hasNext()).isTrue().as("Expected to be true");
Review Comment:
testing idempotency of hasNext. I will add a comment to make it clear
--
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-sidecar] frankgh commented on a diff in pull request #45: CEP-28: Implement Bulk API endpoints and introduce the Sidecar Client to Support Bulk Analytics
Posted by "frankgh (via GitHub)" <gi...@apache.org>.
frankgh commented on code in PR #45:
URL: https://github.com/apache/cassandra-sidecar/pull/45#discussion_r1194294163
##########
client/src/testFixtures/java/org/apache/cassandra/sidecar/client/request/RingRequestForKeyspaceTestParameters.java:
##########
@@ -0,0 +1,77 @@
+/*
+ * 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.sidecar.client.request;
+
+import java.util.List;
+import java.util.stream.Collectors;
+import java.util.stream.StreamSupport;
+
+import org.apache.cassandra.sidecar.client.RequestContext;
+import org.apache.cassandra.sidecar.common.ApiEndpointsV1;
+import org.apache.cassandra.sidecar.common.data.RingEntry;
+import org.apache.cassandra.sidecar.common.data.RingResponse;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+/**
+ * Unit tests for client requests accessing the ring endpoint for a given keyspace
+ */
+public class RingRequestForKeyspaceTestParameters implements RequestTestParameters<RingResponse>
+{
+ public static final String KEYSPACE = "tutorialspoint";
Review Comment:
it should just be testkeyspace or something like that. I will update it
--
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-sidecar] frankgh commented on pull request #45: CEP-28: Implement Bulk API endpoints and introduce the Sidecar Client to Support Bulk Analytics
Posted by "frankgh (via GitHub)" <gi...@apache.org>.
frankgh commented on PR #45:
URL: https://github.com/apache/cassandra-sidecar/pull/45#issuecomment-1548755006
Thanks for the review @yifan-c . I've pushed a few commits and I hope I've addressed your comments fully. Let me know if there is anything additional to address
--
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-sidecar] yifan-c commented on a diff in pull request #45: CEP-28: Implement Bulk API endpoints and introduce the Sidecar Client to Support Bulk Analytics
Posted by "yifan-c (via GitHub)" <gi...@apache.org>.
yifan-c commented on code in PR #45:
URL: https://github.com/apache/cassandra-sidecar/pull/45#discussion_r1195483677
##########
cassandra40/src/main/java/org/apache/cassandra/sidecar/cassandra40/TokenRangeReplicas.java:
##########
@@ -0,0 +1,515 @@
+/*
+ * 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.sidecar.cassandra40;
+
+import java.math.BigInteger;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Set;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import com.google.common.base.Objects;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.VisibleForTesting;
+
+
+/**
+ * Representation of a token range and the corresponding mapping to replica-set hosts. The range corresponds to
+ * an exclusive start range and inclusive end range {@code (start, end]}.
+ */
+public class TokenRangeReplicas implements Comparable<TokenRangeReplicas>
+{
+ private final BigInteger start;
+ private final BigInteger end;
+
+ private final Partitioner partitioner;
+
+ private final Set<String> replicaSet;
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(TokenRangeReplicas.class);
+
+ public TokenRangeReplicas(BigInteger start, BigInteger end, Partitioner partitioner, Set<String> replicaSet)
+ {
+ this.start = start;
+ this.end = end;
+ this.partitioner = partitioner;
+ this.replicaSet = replicaSet;
+ }
+
+
+ public BigInteger start()
+ {
+ return start;
+ }
+
+ public BigInteger end()
+ {
+ return end;
+ }
+
+ public Set<String> replicaSet()
+ {
+ return replicaSet;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public int compareTo(@NotNull TokenRangeReplicas other)
+ {
+ validateMatchingPartitioner(other);
+
+ BigInteger maxValue = this.partitioner.maxToken;
+ if (this.start.compareTo(other.start) == 0)
+ {
+ if (this.end.equals(maxValue)) return 1;
+ else if (other.end.equals(maxValue)) return -1;
+ else return this.end.compareTo(other.end);
+ }
+ else return this.start.compareTo(other.start);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public boolean equals(Object o)
+ {
+ if (!(o instanceof TokenRangeReplicas))
+ {
+ return false;
+ }
+ TokenRangeReplicas that = (TokenRangeReplicas) o;
+ return (this.start.equals(that.start) && this.end.equals(that.end) && this.partitioner == that.partitioner);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public int hashCode()
+ {
+ return Objects.hashCode(start, end, partitioner);
Review Comment:
`Objects.hash`
--
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-sidecar] frankgh commented on a diff in pull request #45: CEP-28: Implement Bulk API endpoints and introduce the Sidecar Client to Support Bulk Analytics
Posted by "frankgh (via GitHub)" <gi...@apache.org>.
frankgh commented on code in PR #45:
URL: https://github.com/apache/cassandra-sidecar/pull/45#discussion_r1192582408
##########
src/test/resources/sidecar_with_single_multiple_instances.yaml:
##########
@@ -38,6 +38,8 @@ sidecar:
- stream_requests_per_sec: 5000
- delay_sec: 5
- timeout_sec: 10
+ - allowable_time_skew_in_minutes: 60
Review Comment:
this is configurable. Do you have a different number in mind to suggest?
--
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-sidecar] frankgh commented on a diff in pull request #45: CEP-28: Implement Bulk API endpoints and introduce the Sidecar Client to Support Bulk Analytics
Posted by "frankgh (via GitHub)" <gi...@apache.org>.
frankgh commented on code in PR #45:
URL: https://github.com/apache/cassandra-sidecar/pull/45#discussion_r1192843758
##########
cassandra40/build.gradle:
##########
@@ -12,7 +13,34 @@ repositories {
mavenCentral()
}
+test {
+ useJUnitPlatform()
+}
+
dependencies {
- compile project(":common")
- implementation('org.jetbrains:annotations:23.0.0')
+ implementation(project(":common"))
+ compileOnly('org.jetbrains:annotations:23.0.0')
+ compileOnly('com.datastax.cassandra:cassandra-driver-core:3.11.3')
+ implementation("com.google.guava:guava:${project.rootProject.guavaVersion}")
+ implementation("org.slf4j:slf4j-api:${project.slf4jVersion}")
+
+ testImplementation "org.junit.jupiter:junit-jupiter-api:${project.junitVersion}"
+ testImplementation "org.junit.jupiter:junit-jupiter-params:${project.junitVersion}"
+ testImplementation "org.assertj:assertj-core:3.24.2"
+ testRuntimeOnly "org.junit.jupiter:junit-jupiter-engine:${project.junitVersion}"
+
+ testImplementation('org.mockito:mockito-core:4.10.0')
+ testImplementation('org.mockito:mockito-inline:4.10.0')
+
+}
+
+publishing {
Review Comment:
Will skip for now. I think we should create a JIRA to upgrade gradle and do this as part of that effort. What do you think?
--
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-sidecar] yifan-c commented on a diff in pull request #45: CEP-28: Implement Bulk API endpoints and introduce the Sidecar Client to Support Bulk Analytics
Posted by "yifan-c (via GitHub)" <gi...@apache.org>.
yifan-c commented on code in PR #45:
URL: https://github.com/apache/cassandra-sidecar/pull/45#discussion_r1192846428
##########
cassandra40/src/main/java/org/apache/cassandra/sidecar/cassandra40/TokenRangeReplicas.java:
##########
@@ -0,0 +1,415 @@
+/*
+ * 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.sidecar.cassandra40;
+
+import java.math.BigInteger;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Set;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import com.google.common.base.Objects;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.jetbrains.annotations.NotNull;
+
+
+/**
+ * Representation of a token range and the corresponding mapping to replica-set hosts
+ */
+public class TokenRangeReplicas implements Comparable<TokenRangeReplicas>
+{
+ private final BigInteger start;
+ private final BigInteger end;
+
+ private final Partitioner partitioner;
+
+ private final Set<String> replicaSet;
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(TokenRangeReplicas.class);
+
+ public TokenRangeReplicas(BigInteger start, BigInteger end, Partitioner partitioner, Set<String> replicaSet)
+ {
+ this.start = start;
+ this.end = end;
+ this.partitioner = partitioner;
+ this.replicaSet = replicaSet;
+ }
+
+
+ public BigInteger start()
+ {
+ return start;
+ }
+
+ public BigInteger end()
+ {
+ return end;
+ }
+
+ public Set<String> replicaSet()
+ {
+ return replicaSet;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public int compareTo(@NotNull TokenRangeReplicas other)
+ {
+ if (this.partitioner != other.partitioner)
+ throw new IllegalStateException("Token ranges being compared do not have the same partitioner");
+
+ BigInteger maxValue = this.partitioner.maxToken;
+ if (this.start.compareTo(other.start) == 0)
+ {
+ if (this.end.equals(maxValue)) return 1;
+ else if (other.end.equals(maxValue)) return -1;
+ else return this.end.compareTo(other.end);
+ }
+ else return this.start.compareTo(other.start);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public boolean equals(Object o)
+ {
+ if (!(o instanceof TokenRangeReplicas))
+ {
+ return false;
+ }
+ TokenRangeReplicas that = (TokenRangeReplicas) o;
+ return (this.start.equals(that.start) && this.end.equals(that.end) && this.partitioner == that.partitioner);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public int hashCode()
+ {
+ return Objects.hashCode(start, end, partitioner);
+ }
+
+ private boolean isWrapAround()
+ {
+ return start.compareTo(end) >= 0;
+ }
+
+ private boolean isSubsetOf(TokenRangeReplicas other)
+ {
+ if (this.partitioner != other.partitioner)
+ throw new IllegalStateException("Token ranges being compared do not have the same partitioner");
+
+ BigInteger maxValue = this.partitioner.maxToken;
+ if (this.start.compareTo(other.start) >= 0)
+ {
+ if (other.end.equals(maxValue)) return true;
+ if (this.end.equals(maxValue)) return false;
+ if (this.end.compareTo(other.end) <= 0) return true;
+ }
+ return false;
+ }
+
+ /**
+ * For subset ranges, this is used to determine if a range is larger than the other by comparing start-end lengths
+ * If both ranges end at the min, we compare starting points to determine the result.
+ * When the left range is the only one ending at min, it is always the larger one since all subsequent ranges
+ * in the sorted range list have to be smaller.
+ *
+ * @param other the next range in the range list to compare
+ * @return true if "this" range is larger than the other
+ */
+ private boolean isLarger(TokenRangeReplicas other)
Review Comment:
1. Please write unit tests for this method.
2. What qualifies a range to be larger? I am still confused after reading the java doc. The first sentence says it compares the lengths, which makes sense. But the later sentences seem to indicate that it also depends on the position of the ranges.
##########
client/src/main/java/org/apache/cassandra/sidecar/client/SidecarInstanceImpl.java:
##########
@@ -0,0 +1,105 @@
+/*
+ * 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.sidecar.client;
+
+import java.util.Objects;
+
+/**
+ * A simple implementation of the {@link SidecarInstance} interface
+ */
+public class SidecarInstanceImpl implements SidecarInstance
+{
+ protected int port;
+ protected String hostname;
+
+ /**
+ * Constructs a new Sidecar instance with the given {@code port} and {@code hostname}
+ *
+ * @param hostname the host name where Sidecar is running
+ * @param port the port where Sidecar is running
+ */
+ public SidecarInstanceImpl(String hostname, int port)
+ {
+ if (port < 1 || port > 65535)
+ {
+ throw new IllegalArgumentException(String.format("Invalid port number for the Sidecar service: %d",
+ port));
+ }
+ this.port = port;
+ this.hostname = Objects.requireNonNull(hostname, "The Sidecar hostname must be non-null");
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public int port()
+ {
+ return port;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public String hostname()
+ {
+ return hostname;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+
Review Comment:
remove the empty line.
##########
cassandra40/src/main/java/org/apache/cassandra/sidecar/cassandra40/TokenRangeReplicas.java:
##########
@@ -0,0 +1,415 @@
+/*
+ * 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.sidecar.cassandra40;
+
+import java.math.BigInteger;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Set;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import com.google.common.base.Objects;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.jetbrains.annotations.NotNull;
+
+
+/**
+ * Representation of a token range and the corresponding mapping to replica-set hosts
Review Comment:
add a sentence to explain which end of the range is exclusive. I would assume `(start, end]`
##########
client/src/main/java/org/apache/cassandra/sidecar/client/RequestContext.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.sidecar.client;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.apache.cassandra.sidecar.client.request.CleanSSTableUploadSessionRequest;
+import org.apache.cassandra.sidecar.client.request.ClearSnapshotRequest;
+import org.apache.cassandra.sidecar.client.request.CreateSnapshotRequest;
+import org.apache.cassandra.sidecar.client.request.GossipInfoRequest;
+import org.apache.cassandra.sidecar.client.request.ImportSSTableRequest;
+import org.apache.cassandra.sidecar.client.request.ListSnapshotFilesRequest;
+import org.apache.cassandra.sidecar.client.request.NodeSettingsRequest;
+import org.apache.cassandra.sidecar.client.request.Request;
+import org.apache.cassandra.sidecar.client.request.RingRequest;
+import org.apache.cassandra.sidecar.client.request.SSTableComponentRequest;
+import org.apache.cassandra.sidecar.client.request.SchemaRequest;
+import org.apache.cassandra.sidecar.client.request.TimeSkewRequest;
+import org.apache.cassandra.sidecar.client.request.TokenRangeReplicasRequest;
+import org.apache.cassandra.sidecar.client.request.UploadSSTableRequest;
+import org.apache.cassandra.sidecar.client.retry.ExponentialBackoffRetryPolicy;
+import org.apache.cassandra.sidecar.client.retry.NoRetryPolicy;
+import org.apache.cassandra.sidecar.client.retry.RetryPolicy;
+import org.apache.cassandra.sidecar.client.selection.InstanceSelectionPolicy;
+import org.apache.cassandra.sidecar.client.selection.SingleInstanceSelectionPolicy;
+import org.apache.cassandra.sidecar.common.utils.HttpRange;
+
+/**
+ * The context for a given request that include the {@link InstanceSelectionPolicy}, the {@link RetryPolicy}, and
+ * the {@link Request}
+ */
+public class RequestContext
+{
+ protected static final SchemaRequest FULL_SCHEMA_REQUEST = new SchemaRequest();
+ protected static final TimeSkewRequest TIME_SKEW_REQUEST = new TimeSkewRequest();
+ protected static final NodeSettingsRequest NODE_SETTINGS_REQUEST = new NodeSettingsRequest();
+ protected static final RingRequest RING_REQUEST = new RingRequest();
Review Comment:
nit: the request objects, as well as the request builder methods below, do not feel should part of `RequestContext`, which supplies the context for a request.
But I think it is fine to leave them as is for now.
##########
cassandra40/src/main/java/org/apache/cassandra/sidecar/cassandra40/TokenRangeReplicas.java:
##########
@@ -0,0 +1,415 @@
+/*
+ * 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.sidecar.cassandra40;
+
+import java.math.BigInteger;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Set;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import com.google.common.base.Objects;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.jetbrains.annotations.NotNull;
+
+
+/**
+ * Representation of a token range and the corresponding mapping to replica-set hosts
+ */
+public class TokenRangeReplicas implements Comparable<TokenRangeReplicas>
+{
+ private final BigInteger start;
+ private final BigInteger end;
+
+ private final Partitioner partitioner;
+
+ private final Set<String> replicaSet;
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(TokenRangeReplicas.class);
+
+ public TokenRangeReplicas(BigInteger start, BigInteger end, Partitioner partitioner, Set<String> replicaSet)
+ {
+ this.start = start;
+ this.end = end;
+ this.partitioner = partitioner;
+ this.replicaSet = replicaSet;
+ }
+
+
+ public BigInteger start()
+ {
+ return start;
+ }
+
+ public BigInteger end()
+ {
+ return end;
+ }
+
+ public Set<String> replicaSet()
+ {
+ return replicaSet;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public int compareTo(@NotNull TokenRangeReplicas other)
+ {
+ if (this.partitioner != other.partitioner)
+ throw new IllegalStateException("Token ranges being compared do not have the same partitioner");
+
+ BigInteger maxValue = this.partitioner.maxToken;
+ if (this.start.compareTo(other.start) == 0)
+ {
+ if (this.end.equals(maxValue)) return 1;
+ else if (other.end.equals(maxValue)) return -1;
+ else return this.end.compareTo(other.end);
+ }
+ else return this.start.compareTo(other.start);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public boolean equals(Object o)
+ {
+ if (!(o instanceof TokenRangeReplicas))
+ {
+ return false;
+ }
+ TokenRangeReplicas that = (TokenRangeReplicas) o;
+ return (this.start.equals(that.start) && this.end.equals(that.end) && this.partitioner == that.partitioner);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public int hashCode()
+ {
+ return Objects.hashCode(start, end, partitioner);
+ }
+
+ private boolean isWrapAround()
+ {
+ return start.compareTo(end) >= 0;
+ }
+
+ private boolean isSubsetOf(TokenRangeReplicas other)
Review Comment:
Does it check if this range is entirely covered by the other range? In other word, the `other` range contains `this` range.
If so, I think the implementation is wrong. See test below
```java
@Test
void testSubsetRelationship()
{
// wraps around
TokenRangeReplicas range1 = new TokenRangeReplicas(BigInteger.valueOf(100), BigInteger.valueOf(-100), Partitioner.Murmur3, new HashSet<>());
TokenRangeReplicas range2 = new TokenRangeReplicas(BigInteger.valueOf(100), Partitioner.Murmur3.maxToken, Partitioner.Murmur3, new HashSet<>());
assertThat(range1.isSubsetOf(range2)).isFalse();
assertThat(range2.isSubsetOf(range1)).isTrue();
}
```
nit: the name could be more succinct if it is called "contains". The implementation needs to be adjusted if being renamed.
##########
client/src/main/java/org/apache/cassandra/sidecar/client/SidecarConfig.java:
##########
@@ -0,0 +1,125 @@
+/*
+ * 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.sidecar.client;
+
+/**
+ * Encapsulates configurations for the {@link SidecarClient}
+ */
+public class SidecarConfig
+{
+ private static final int DEFAULT_MAX_RETRIES = 3;
+ private static final long DEFAULT_RETRY_DELAY_MILLIS = 500L;
+ private static final long DEFAULT_MAX_RETRY_DELAY_MILLIS = 60_000L;
+
+ private final int maxRetries;
+ private final long retryDelayMillis;
+ private final long maxRetryDelayMillis;
+
+ private SidecarConfig(Builder builder)
+ {
+ maxRetries = builder.maxRetries;
+ retryDelayMillis = builder.retryDelayMillis;
+ maxRetryDelayMillis = builder.maxRetryDelayMillis;
+ }
+
+ /**
+ * @return the maximum number of times to retry a request
+ */
+ public int maxRetries()
+ {
+ return maxRetries;
+ }
+
+ /**
+ * @return the initial amount of time to wait before retrying a failed request
+ */
+ public long retryDelayMillis()
+ {
+ return retryDelayMillis;
+ }
+
+ /**
+ * @return the maximum amount of time to wait before retrying a failed request
+ */
+ public long maxRetryDelayMillis()
+ {
+ return maxRetryDelayMillis;
+ }
+
+ /**
+ * {@code SidecarConfig} builder static inner class.
+ */
+ public static final class Builder
+ {
+ private int maxRetries = DEFAULT_MAX_RETRIES;
+ private long retryDelayMillis = DEFAULT_RETRY_DELAY_MILLIS;
+ private long maxRetryDelayMillis = DEFAULT_MAX_RETRY_DELAY_MILLIS;
+
+ public Builder()
+ {
+ }
Review Comment:
It can be removed.
##########
checkstyle.xml:
##########
@@ -139,6 +139,7 @@ page at http://checkstyle.sourceforge.net/config.html -->
<module name="JavadocType">
<property name="scope" value="protected" />
+ <property name="allowUnknownTags" value="true" />
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.
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-sidecar] frankgh commented on a diff in pull request #45: CEP-28: Implement Bulk API endpoints and introduce the Sidecar Client to Support Bulk Analytics
Posted by "frankgh (via GitHub)" <gi...@apache.org>.
frankgh commented on code in PR #45:
URL: https://github.com/apache/cassandra-sidecar/pull/45#discussion_r1194173811
##########
cassandra40/src/main/java/org/apache/cassandra/sidecar/cassandra40/TokenRangeReplicas.java:
##########
@@ -0,0 +1,415 @@
+/*
+ * 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.sidecar.cassandra40;
+
+import java.math.BigInteger;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Set;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import com.google.common.base.Objects;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.jetbrains.annotations.NotNull;
+
+
+/**
+ * Representation of a token range and the corresponding mapping to replica-set hosts
+ */
+public class TokenRangeReplicas implements Comparable<TokenRangeReplicas>
+{
+ private final BigInteger start;
+ private final BigInteger end;
+
+ private final Partitioner partitioner;
+
+ private final Set<String> replicaSet;
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(TokenRangeReplicas.class);
+
+ public TokenRangeReplicas(BigInteger start, BigInteger end, Partitioner partitioner, Set<String> replicaSet)
+ {
+ this.start = start;
+ this.end = end;
+ this.partitioner = partitioner;
+ this.replicaSet = replicaSet;
+ }
+
+
+ public BigInteger start()
+ {
+ return start;
+ }
+
+ public BigInteger end()
+ {
+ return end;
+ }
+
+ public Set<String> replicaSet()
+ {
+ return replicaSet;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public int compareTo(@NotNull TokenRangeReplicas other)
+ {
+ if (this.partitioner != other.partitioner)
+ throw new IllegalStateException("Token ranges being compared do not have the same partitioner");
+
+ BigInteger maxValue = this.partitioner.maxToken;
+ if (this.start.compareTo(other.start) == 0)
+ {
+ if (this.end.equals(maxValue)) return 1;
+ else if (other.end.equals(maxValue)) return -1;
+ else return this.end.compareTo(other.end);
+ }
+ else return this.start.compareTo(other.start);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public boolean equals(Object o)
+ {
+ if (!(o instanceof TokenRangeReplicas))
+ {
+ return false;
+ }
+ TokenRangeReplicas that = (TokenRangeReplicas) o;
+ return (this.start.equals(that.start) && this.end.equals(that.end) && this.partitioner == that.partitioner);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public int hashCode()
+ {
+ return Objects.hashCode(start, end, partitioner);
+ }
+
+ private boolean isWrapAround()
+ {
+ return start.compareTo(end) >= 0;
+ }
+
+ private boolean isSubsetOf(TokenRangeReplicas other)
Review Comment:
adding this test and providing a fixed implementation
--
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-sidecar] yifan-c commented on a diff in pull request #45: CEP-28: Implement Bulk API endpoints and introduce the Sidecar Client to Support Bulk Analytics
Posted by "yifan-c (via GitHub)" <gi...@apache.org>.
yifan-c commented on code in PR #45:
URL: https://github.com/apache/cassandra-sidecar/pull/45#discussion_r1194167826
##########
client/src/test/java/org/apache/cassandra/sidecar/client/retry/BasicRetryPolicyTest.java:
##########
@@ -0,0 +1,376 @@
+/*
+ * 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.sidecar.client.retry;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CompletionException;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.stream.Stream;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.junit.jupiter.params.provider.ValueSource;
+
+import org.apache.cassandra.sidecar.client.HttpResponse;
+import org.apache.cassandra.sidecar.client.exception.ResourceNotFoundException;
+import org.apache.cassandra.sidecar.client.exception.RetriesExhaustedException;
+import org.apache.cassandra.sidecar.client.exception.UnexpectedStatusCodeException;
+import org.apache.cassandra.sidecar.client.request.Request;
+
+import static io.netty.handler.codec.http.HttpResponseStatus.ACCEPTED;
+import static io.netty.handler.codec.http.HttpResponseStatus.BAD_GATEWAY;
+import static io.netty.handler.codec.http.HttpResponseStatus.BAD_REQUEST;
+import static io.netty.handler.codec.http.HttpResponseStatus.CONFLICT;
+import static io.netty.handler.codec.http.HttpResponseStatus.EXPECTATION_FAILED;
+import static io.netty.handler.codec.http.HttpResponseStatus.FAILED_DEPENDENCY;
+import static io.netty.handler.codec.http.HttpResponseStatus.FORBIDDEN;
+import static io.netty.handler.codec.http.HttpResponseStatus.GATEWAY_TIMEOUT;
+import static io.netty.handler.codec.http.HttpResponseStatus.GONE;
+import static io.netty.handler.codec.http.HttpResponseStatus.HTTP_VERSION_NOT_SUPPORTED;
+import static io.netty.handler.codec.http.HttpResponseStatus.INSUFFICIENT_STORAGE;
+import static io.netty.handler.codec.http.HttpResponseStatus.INTERNAL_SERVER_ERROR;
+import static io.netty.handler.codec.http.HttpResponseStatus.LENGTH_REQUIRED;
+import static io.netty.handler.codec.http.HttpResponseStatus.LOCKED;
+import static io.netty.handler.codec.http.HttpResponseStatus.METHOD_NOT_ALLOWED;
+import static io.netty.handler.codec.http.HttpResponseStatus.MISDIRECTED_REQUEST;
+import static io.netty.handler.codec.http.HttpResponseStatus.NETWORK_AUTHENTICATION_REQUIRED;
+import static io.netty.handler.codec.http.HttpResponseStatus.NOT_ACCEPTABLE;
+import static io.netty.handler.codec.http.HttpResponseStatus.NOT_EXTENDED;
+import static io.netty.handler.codec.http.HttpResponseStatus.NOT_FOUND;
+import static io.netty.handler.codec.http.HttpResponseStatus.NOT_IMPLEMENTED;
+import static io.netty.handler.codec.http.HttpResponseStatus.OK;
+import static io.netty.handler.codec.http.HttpResponseStatus.PAYMENT_REQUIRED;
+import static io.netty.handler.codec.http.HttpResponseStatus.PRECONDITION_FAILED;
+import static io.netty.handler.codec.http.HttpResponseStatus.PRECONDITION_REQUIRED;
+import static io.netty.handler.codec.http.HttpResponseStatus.PROXY_AUTHENTICATION_REQUIRED;
+import static io.netty.handler.codec.http.HttpResponseStatus.REQUESTED_RANGE_NOT_SATISFIABLE;
+import static io.netty.handler.codec.http.HttpResponseStatus.REQUEST_HEADER_FIELDS_TOO_LARGE;
+import static io.netty.handler.codec.http.HttpResponseStatus.REQUEST_TIMEOUT;
+import static io.netty.handler.codec.http.HttpResponseStatus.REQUEST_URI_TOO_LONG;
+import static io.netty.handler.codec.http.HttpResponseStatus.SERVICE_UNAVAILABLE;
+import static io.netty.handler.codec.http.HttpResponseStatus.TOO_MANY_REQUESTS;
+import static io.netty.handler.codec.http.HttpResponseStatus.UNAUTHORIZED;
+import static io.netty.handler.codec.http.HttpResponseStatus.UNPROCESSABLE_ENTITY;
+import static io.netty.handler.codec.http.HttpResponseStatus.UNSUPPORTED_MEDIA_TYPE;
+import static io.netty.handler.codec.http.HttpResponseStatus.UPGRADE_REQUIRED;
+import static io.netty.handler.codec.http.HttpResponseStatus.VARIANT_ALSO_NEGOTIATES;
+import static io.netty.handler.codec.rtsp.RtspResponseStatuses.REQUEST_ENTITY_TOO_LARGE;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
+import static org.assertj.core.api.Fail.fail;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+/**
+ * Unit tests for the {@link BasicRetryPolicy}
+ */
+class BasicRetryPolicyTest
+{
+ HttpResponse mockResponse;
+ Request mockRequest;
+ RetryPolicy defaultBasicRetryPolicy;
+ Map<String, List<String>> headersMap;
+
+ @BeforeEach
+ void setup()
+ {
+ defaultBasicRetryPolicy = new BasicRetryPolicy();
+ headersMap = new HashMap<>();
+ mockResponse = mock(HttpResponse.class);
+ mockRequest = mock(Request.class);
+ when(mockResponse.headers()).thenReturn(headersMap);
+ when(mockRequest.requestURI()).thenReturn("/api/uri");
+ }
+
+ @ParameterizedTest(name = "{index} => canRetryOnADifferentHost={0}")
+ @ValueSource(booleans = { true, false })
+ void testRetriesWhenThrowableIsProvided(boolean canRetryOnADifferentHost)
+ {
+ IllegalArgumentException throwable = new IllegalArgumentException("Connection Refused");
+ testWithRetries(mockRequest, null, throwable, 3, 100, canRetryOnADifferentHost);
+ }
+
+ @Test
+ void testRetriesOnInternalServerErrorStatusCode()
+ {
+ when(mockResponse.statusCode()).thenReturn(INTERNAL_SERVER_ERROR.code());
+ testWithRetries(mockRequest, mockResponse, null, 5, 200, false);
+ testWithRetries(mockRequest, mockResponse, null, 5, 200, true);
+ }
+
+ @Test
+ void testCompletesWithOKStatusCode() throws ExecutionException, InterruptedException
+ {
+ when(mockResponse.statusCode()).thenReturn(OK.code());
+
+ CompletableFuture<HttpResponse> future = new CompletableFuture<>();
+ defaultBasicRetryPolicy.onResponse(future, mockRequest, mockResponse, null, 1, false,
+ (attempts, retryDelayMillis) -> fail("Should never retry"));
+ future.join();
+ assertThat(future.isDone()).isTrue();
+ assertThat(future.get()).isSameAs(mockResponse);
+ }
+
+ @ParameterizedTest(name = "{index} => canRetryOnADifferentHost={0}")
+ @ValueSource(booleans = { true, false })
+ void testCompletesWithNotFoundStatusCode(boolean canRetryOnADifferentHost)
Review Comment:
👍
##########
client/src/test/java/org/apache/cassandra/sidecar/client/retry/RunnableOnStatusCodeRetryPolicyTest.java:
##########
@@ -0,0 +1,101 @@
+/*
+ * 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.sidecar.client.retry;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import io.netty.handler.codec.http.HttpResponseStatus;
+import org.apache.cassandra.sidecar.client.HttpResponse;
+import org.apache.cassandra.sidecar.client.request.Request;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Fail.fail;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+/**
+ * Unit tests for the {@link RunnableOnStatusCodeRetryPolicy} class
+ */
+class RunnableOnStatusCodeRetryPolicyTest
+{
+ private static final Logger LOGGER = LoggerFactory.getLogger(RunnableOnStatusCodeRetryPolicyTest.class);
Review Comment:
not used.
##########
client/src/test/java/org/apache/cassandra/sidecar/client/selection/OrderedInstanceSelectionPolicyTest.java:
##########
@@ -0,0 +1,79 @@
+/*
+ * 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.sidecar.client.selection;
+
+import java.util.Arrays;
+import java.util.Iterator;
+import java.util.List;
+import java.util.NoSuchElementException;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import org.apache.cassandra.sidecar.client.SidecarInstance;
+import org.apache.cassandra.sidecar.client.SidecarInstancesProvider;
+import org.apache.cassandra.sidecar.client.SimpleSidecarInstancesProvider;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
+import static org.mockito.Mockito.mock;
+
+/**
+ * Unit tests for the {@link OrderedInstanceSelectionPolicy}
+ */
+class OrderedInstanceSelectionPolicyTest
+{
+ List<SidecarInstance> mockInstanceList;
+ SidecarInstance mockInstance1;
+ SidecarInstance mockInstance2;
+ SidecarInstance mockInstance3;
+ SidecarInstance mockInstance4;
+
+ @BeforeEach
+ void setup()
+ {
+ mockInstance1 = mock(SidecarInstance.class);
+ mockInstance2 = mock(SidecarInstance.class);
+ mockInstance3 = mock(SidecarInstance.class);
+ mockInstance4 = mock(SidecarInstance.class);
+ mockInstanceList = Arrays.asList(mockInstance1, mockInstance2, mockInstance3, mockInstance4);
+ }
+
+ @Test
+ public void testIterator()
+ {
+
+ SidecarInstancesProvider provider = new SimpleSidecarInstancesProvider(mockInstanceList);
+ InstanceSelectionPolicy instanceSelectionPolicy = new OrderedInstanceSelectionPolicy(provider);
+ Iterator<SidecarInstance> iterator = instanceSelectionPolicy.iterator();
+
+ assertThat(iterator.hasNext()).isTrue();
+ assertThat(iterator.hasNext()).isTrue().as("Expected to be true");
Review Comment:
nit: duplication
##########
client/src/test/java/org/apache/cassandra/sidecar/client/selection/RandomInstanceSelectionPolicyTest.java:
##########
@@ -0,0 +1,72 @@
+/*
+ * 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.sidecar.client.selection;
+
+import java.util.Arrays;
+import java.util.Iterator;
+import java.util.List;
+import java.util.NoSuchElementException;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import org.apache.cassandra.sidecar.client.SidecarInstance;
+import org.apache.cassandra.sidecar.client.SidecarInstancesProvider;
+import org.apache.cassandra.sidecar.client.SimpleSidecarInstancesProvider;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
+import static org.mockito.Mockito.mock;
+
+/**
+ * Unit tests for the {@link RandomInstanceSelectionPolicy}
+ */
+class RandomInstanceSelectionPolicyTest
+{
+ List<SidecarInstance> mockInstanceList;
+
+ @BeforeEach
+ void setup()
+ {
+ mockInstanceList = Arrays.asList(mock(SidecarInstance.class), mock(SidecarInstance.class),
+ mock(SidecarInstance.class), mock(SidecarInstance.class)
+ );
+ }
+
+ @Test
+ public void testIterator()
+ {
+ SidecarInstancesProvider provider = new SimpleSidecarInstancesProvider(mockInstanceList);
+ InstanceSelectionPolicy instanceSelectionPolicy = new RandomInstanceSelectionPolicy(provider);
+ Iterator<SidecarInstance> iterator = instanceSelectionPolicy.iterator();
+
+ assertThat(iterator.hasNext()).isTrue();
+ assertThat(iterator.hasNext()).isTrue().as("Expected to be true");
Review Comment:
nit: duplication
##########
client/src/testFixtures/java/org/apache/cassandra/sidecar/client/request/RingRequestForKeyspaceTestParameters.java:
##########
@@ -0,0 +1,77 @@
+/*
+ * 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.sidecar.client.request;
+
+import java.util.List;
+import java.util.stream.Collectors;
+import java.util.stream.StreamSupport;
+
+import org.apache.cassandra.sidecar.client.RequestContext;
+import org.apache.cassandra.sidecar.common.ApiEndpointsV1;
+import org.apache.cassandra.sidecar.common.data.RingEntry;
+import org.apache.cassandra.sidecar.common.data.RingResponse;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+/**
+ * Unit tests for client requests accessing the ring endpoint for a given keyspace
+ */
+public class RingRequestForKeyspaceTestParameters implements RequestTestParameters<RingResponse>
+{
+ public static final String KEYSPACE = "tutorialspoint";
Review Comment:
hmm... it seems to be the name of a website?
##########
common/src/main/java/org/apache/cassandra/sidecar/common/data/GossipInfoResponse.java:
##########
@@ -0,0 +1,292 @@
+/*
+ * 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.sidecar.common.data;
+
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+
+import static org.apache.cassandra.sidecar.common.data.GossipInfoResponse.GossipField.DC;
+import static org.apache.cassandra.sidecar.common.data.GossipInfoResponse.GossipField.DISK_USAGE;
+import static org.apache.cassandra.sidecar.common.data.GossipInfoResponse.GossipField.GENERATION;
+import static org.apache.cassandra.sidecar.common.data.GossipInfoResponse.GossipField.HEARTBEAT;
+import static org.apache.cassandra.sidecar.common.data.GossipInfoResponse.GossipField.HOST_ID;
+import static org.apache.cassandra.sidecar.common.data.GossipInfoResponse.GossipField.INTERNAL_ADDRESS_AND_PORT;
+import static org.apache.cassandra.sidecar.common.data.GossipInfoResponse.GossipField.INTERNAL_IP;
+import static org.apache.cassandra.sidecar.common.data.GossipInfoResponse.GossipField.LOAD;
+import static org.apache.cassandra.sidecar.common.data.GossipInfoResponse.GossipField.NATIVE_ADDRESS_AND_PORT;
+import static org.apache.cassandra.sidecar.common.data.GossipInfoResponse.GossipField.NET_VERSION;
+import static org.apache.cassandra.sidecar.common.data.GossipInfoResponse.GossipField.RACK;
+import static org.apache.cassandra.sidecar.common.data.GossipInfoResponse.GossipField.RELEASE_VERSION;
+import static org.apache.cassandra.sidecar.common.data.GossipInfoResponse.GossipField.REMOVAL_COORDINATOR;
+import static org.apache.cassandra.sidecar.common.data.GossipInfoResponse.GossipField.RPC_ADDRESS;
+import static org.apache.cassandra.sidecar.common.data.GossipInfoResponse.GossipField.RPC_READY;
+import static org.apache.cassandra.sidecar.common.data.GossipInfoResponse.GossipField.SCHEMA;
+import static org.apache.cassandra.sidecar.common.data.GossipInfoResponse.GossipField.SEVERITY;
+import static org.apache.cassandra.sidecar.common.data.GossipInfoResponse.GossipField.SSTABLE_VERSIONS;
+import static org.apache.cassandra.sidecar.common.data.GossipInfoResponse.GossipField.STATUS;
+import static org.apache.cassandra.sidecar.common.data.GossipInfoResponse.GossipField.STATUS_WITH_PORT;
+import static org.apache.cassandra.sidecar.common.data.GossipInfoResponse.GossipField.TOKENS;
+import static org.apache.cassandra.sidecar.common.data.GossipInfoResponse.GossipField.read;
+
+/**
+ * A class representing the response of the cassandra gossip endpoint
+ */
+public class GossipInfoResponse extends HashMap<String, GossipInfoResponse.GossipInfo>
+{
+ /**
+ * Data accessor for reading Gossip states
+ */
+ public static class GossipInfo extends HashMap<String, String>
+ {
+ /**
+ * Converts the key, if it is using the UPPER UNDERSCORE format, into camel case.
+ * Then, put the new key and value.
+ *
+ * @param snakeCaseKey the key to convert
+ * @param value the value for the gossip info entry
+ */
+ public void camelizeKeyAndPut(String snakeCaseKey, String value)
+ {
+ String key = toLowerCamelCase(snakeCaseKey.toUpperCase());
+ super.put(key, value);
+ }
+
+ @NotNull
+ public String generation()
+ {
+ return read(this, GENERATION);
+ }
+
+ @NotNull
+ public String heartbeat()
+ {
+ return read(this, HEARTBEAT);
+ }
+
+ @Nullable
+ public String status()
+ {
+ return read(this, STATUS);
+ }
+
+ @Nullable
+ public String load()
+ {
+ return read(this, LOAD);
+ }
+
+ /**
+ * @return schema version, uuid string
+ */
+ @Nullable
+ public String schema()
+ {
+ return read(this, SCHEMA);
+ }
+
+ /**
+ * @return datacenter name
+ */
+ @Nullable
+ public String datacenter()
+ {
+ return read(this, DC);
+ }
+
+ /**
+ * @return rack name
+ */
+ @Nullable
+ public String rack()
+ {
+ return read(this, RACK);
+ }
+
+ @Nullable
+ public String releaseVersion()
+ {
+ return read(this, RELEASE_VERSION);
+ }
+
+ @Nullable
+ public String removalCoordinator()
+ {
+ return read(this, REMOVAL_COORDINATOR);
+ }
+
+ @Nullable
+ public String internalIp()
+ {
+ return read(this, INTERNAL_IP);
+ }
+
+ @Nullable
+ public String rpcAddress()
+ {
+ return read(this, RPC_ADDRESS);
+ }
+
+ @Nullable
+ public String severity()
+ {
+ return read(this, SEVERITY);
+ }
+
+ @Nullable
+ public String netVersion()
+ {
+ return read(this, NET_VERSION);
+ }
+
+ @Nullable
+ public String hostId()
+ {
+ return read(this, HOST_ID);
+ }
+
+ @Nullable
+ public String tokens()
+ {
+ return read(this, TOKENS);
+ }
+
+ @Nullable
+ public Boolean rpcReady()
+ {
+ String value = read(this, RPC_READY);
+ return value == null ? null : Boolean.valueOf(value);
+ }
+
+ @Nullable
+ public String internalAddressAndPort()
+ {
+ return read(this, INTERNAL_ADDRESS_AND_PORT);
+ }
+
+ @Nullable
+ public String nativeAddressAndPort()
+ {
+ return read(this, NATIVE_ADDRESS_AND_PORT);
+ }
+
+ @Nullable
+ public String statusWithPort()
+ {
+ return read(this, STATUS_WITH_PORT);
+ }
+
+ @Nullable
+ public List<String> sstableVersions()
+ {
+ String value = read(this, SSTABLE_VERSIONS);
+ return value == null ? null : Arrays.asList(value.split(","));
+ }
+
+ @Nullable
+ public String diskUsage()
+ {
+ return read(this, DISK_USAGE);
+ }
+ }
+
+ /**
+ * Declares all fields that gossip info can possibly contain.
+ *
+ * <p>Note: When adding a new field, make sure there is a pairing access method defined in {@link GossipInfo}.
+ */
+ protected enum GossipField
+ {
+ GENERATION,
+ HEARTBEAT,
+
+ // Below are copied from org.apache.cassandra.gms.ApplicationState
+ // Note: that all padding fields are not included.
+ @Deprecated STATUS, //Deprecated and unsued in 4.0, stop publishing in 5.0, reclaim in 6.0
Review Comment:
```suggestion
@Deprecated STATUS, //Deprecated and unused in 4.0, stop publishing in 5.0, reclaim in 6.0
```
##########
client/src/test/java/org/apache/cassandra/sidecar/client/retry/ExponentialBackoffRetryPolicyTest.java:
##########
@@ -0,0 +1,139 @@
+/*
+ * 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.sidecar.client.retry;
+
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CompletionException;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.atomic.AtomicLong;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+
+import org.apache.cassandra.sidecar.client.HttpResponse;
+import org.apache.cassandra.sidecar.client.exception.RetriesExhaustedException;
+import org.apache.cassandra.sidecar.client.request.Request;
+
+import static io.netty.handler.codec.http.HttpResponseStatus.INTERNAL_SERVER_ERROR;
+import static io.netty.handler.codec.http.HttpResponseStatus.OK;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
+import static org.assertj.core.api.Fail.fail;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+class ExponentialBackoffRetryPolicyTest
+{
+ Request mockRequest;
+ HttpResponse mockResponse;
+
+ @BeforeEach
+ public void setup()
+ {
+ mockRequest = mock(Request.class);
+ mockResponse = mock(HttpResponse.class);
+ when(mockRequest.requestURI()).thenReturn("/api/uri");
+ }
+
+ @Test
+ void testOverflows()
+ {
+ long delay = new ExponentialBackoffRetryPolicy(1, 1, 0)
+ .retryDelayMillis(66); // 2 ^ 63 + 1 overflows
Review Comment:
It should be `64` instead of `66`. `Long.MAX_VALUE == 2 ^ 63`. So to trigger the current overflow check (which is not complete), the input attempts should be 63 + 1 = 64.
The reason why the current check is not complete can be demoed in this test, which fails.
```java
delay = new ExponentialBackoffRetryPolicy(1, 8, 0)
.retryDelayMillis(63); // 2 ^ 62 does not overflow, but 2 ^ 62 * 8 overflows. It should cap the value at MAX_VALUE.
assertThat(delay).isEqualTo(Long.MAX_VALUE);
```
##########
client/src/test/java/org/apache/cassandra/sidecar/client/selection/SingleInstanceSelectionPolicyTest.java:
##########
@@ -0,0 +1,56 @@
+/*
+ * 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.sidecar.client.selection;
+
+import java.util.Iterator;
+import java.util.NoSuchElementException;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import org.apache.cassandra.sidecar.client.SidecarInstance;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
+import static org.mockito.Mockito.mock;
+
+class SingleInstanceSelectionPolicyTest
+{
+ SidecarInstance mockSidecarInstance;
+
+ @BeforeEach
+ void setup()
+ {
+ mockSidecarInstance = mock(SidecarInstance.class);
+ }
+
+ @Test
+ void testIterator()
+ {
+ InstanceSelectionPolicy instanceSelectionPolicy = new SingleInstanceSelectionPolicy(mockSidecarInstance);
+ Iterator<SidecarInstance> iterator = instanceSelectionPolicy.iterator();
+
+ assertThat(iterator.hasNext()).isTrue();
+ assertThat(iterator.hasNext()).isTrue().as("Expected to be true");
Review Comment:
nit: duplication
##########
client/src/testFixtures/java/org/apache/cassandra/sidecar/client/request/GossipInfoRequestTestParameters.java:
##########
@@ -0,0 +1,72 @@
+/*
+ * 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.sidecar.client.request;
+
+import org.apache.cassandra.sidecar.client.RequestContext;
+import org.apache.cassandra.sidecar.common.ApiEndpointsV1;
+import org.apache.cassandra.sidecar.common.data.GossipInfoResponse;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+/**
+ * Unit tests for client requests accessing the gossip info endpoint
+ */
+public class GossipInfoRequestTestParameters implements RequestTestParameters<GossipInfoResponse>
+{
+ @Override
+ public RequestContext.Builder specificRequest(RequestContext.Builder requestContextBuilder)
+ {
+ return requestContextBuilder.gossipInfoRequest();
+ }
+
+ @Override
+ public String okResponseBody()
+ {
+ return "{\"/127.0.0.3:7000\":{\"generation\":\"1679961466\"," +
+ "\"schema\":\"4994b214-7a05-35ea-a11c-d092a554dd5d\",\"rack\":\"101000301\"," +
+ "\"heartbeat\":\"2114\",\"releaseVersion\":\"4.0.8\"," +
+ "\"hostId\":\"be19c254-becb-40b9-8951-30c589c7028e\",\"nativeAddressAndPort\":\"127.0.0.3:9042\"," +
+ "\"load\":\"89083.0\",\"sstableVersions\":\"big-nb\",\"tokens\":\"<hidden>\",\"rpcReady\":\"true\"," +
+ "\"dc\":\"LO\",\"netVersion\":\"12\",\"statusWithPort\":\"NORMAL,3074457345618258602\"}," +
+ "\"/127.0.0.1:7000\":{\"generation\":\"1679961466\"," +
+ "\"schema\":\"4994b214-7a05-35ea-a11c-d092a554dd5d\",\"rack\":\"101000101\",\"heartbeat\":\"2108\"," +
+ "\"releaseVersion\":\"4.0.8\",\"rpcAddress\":\"172.17.0.2\"," +
+ "\"hostId\":\"33cae238-8203-41c1-880f-8cdf98ee6720\",\"nativeAddressAndPort\":\"172.17.0.2:9042\"," +
+ "\"load\":\"89082.0\",\"sstableVersions\":\"big-nb\",\"tokens\":\"<hidden>\",\"rpcReady\":\"true\"," +
+ "\"status\":\"NORMAL,-9223372036854775808\",\"dc\":\"LO\",\"netVersion\":\"12\",\"statusWithPort\":" +
+ "\"NORMAL,-9223372036854775808\"},\"/127.0.0.2:7000\":{\"generation\":\"1679961465\"," +
+ "\"schema\":\"4994b214-7a05-35ea-a11c-d092a554dd5d\",\"rack\":\"101000201\",\"heartbeat\":\"2108\"," +
+ "\"releaseVersion\":\"4.0.8\",\"hostId\":\"dba02656-ea8c-4a1d-8011-cbc0dab5f411\"," +
+ "\"nativeAddressAndPort\":\"127.0.0.2:9042\",\"load\":\"89084.0\",\"sstableVersions\":\"big-nb\"," +
+ "\"tokens\":\"<hidden>\",\"rpcReady\":\"true\",\"dc\":\"LO\",\"netVersion\":\"12\"," +
+ "\"statusWithPort\":\"NORMAL,-3074457345618258603\"}}[root@b77ac3582e25 /]";
Review Comment:
`[root@b77ac3582e25 /]`??
Btw, the nit on preparing the response body is to build a map and serialize into json. This way, the code reads more structured, instead of a large block of string. Feel free to ignore the nit though.
##########
common/src/main/java/org/apache/cassandra/sidecar/common/CassandraAdapterDelegate.java:
##########
@@ -145,47 +124,73 @@ private void healthCheckInternal()
Row oneResult = activeSession.execute("select release_version, partitioner from system.local")
.one();
- String releaseVersion = oneResult.getString("release_version");
- // update the nodeSettings cache.
// Note that within the scope of this method, we should keep on using the local releaseVersion
- nodeSettings = new NodeSettings(releaseVersion, oneResult.getString("partitioner"));
- // this might swap the adapter out
- SimpleCassandraVersion newVersion = SimpleCassandraVersion.create(releaseVersion);
- if (!newVersion.equals(currentVersion))
+ String releaseVersion = oneResult.getString("release_version");
+ NodeSettings newNodeSettings = new NodeSettings(releaseVersion, oneResult.getString("partitioner"));
+ if (!newNodeSettings.equals(nodeSettings))
{
- currentVersion = newVersion;
- adapter = versionProvider.getCassandra(nodeSettings.releaseVersion()).create(cqlSession, jmxClient);
- logger.info("Cassandra version change detected. New adapter loaded: {}", adapter);
+ // update the nodeSettings cache.
+ SimpleCassandraVersion previousVersion = currentVersion;
+ currentVersion = SimpleCassandraVersion.create(releaseVersion);
+ adapter = versionProvider.cassandra(releaseVersion)
+ .create(cqlSessionProvider, jmxClient);
+ nodeSettings = newNodeSettings;
Review Comment:
There is a potential race that set `nodeSettings` to an unexpected value. But since it runs periodically, it should be corrected in the following runs. So.. I think it is acceptable.
##########
client/src/test/java/org/apache/cassandra/sidecar/client/retry/BasicRetryPolicyTest.java:
##########
@@ -0,0 +1,376 @@
+/*
+ * 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.sidecar.client.retry;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CompletionException;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.stream.Stream;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.junit.jupiter.params.provider.ValueSource;
+
+import org.apache.cassandra.sidecar.client.HttpResponse;
+import org.apache.cassandra.sidecar.client.exception.ResourceNotFoundException;
+import org.apache.cassandra.sidecar.client.exception.RetriesExhaustedException;
+import org.apache.cassandra.sidecar.client.exception.UnexpectedStatusCodeException;
+import org.apache.cassandra.sidecar.client.request.Request;
+
+import static io.netty.handler.codec.http.HttpResponseStatus.ACCEPTED;
+import static io.netty.handler.codec.http.HttpResponseStatus.BAD_GATEWAY;
+import static io.netty.handler.codec.http.HttpResponseStatus.BAD_REQUEST;
+import static io.netty.handler.codec.http.HttpResponseStatus.CONFLICT;
+import static io.netty.handler.codec.http.HttpResponseStatus.EXPECTATION_FAILED;
+import static io.netty.handler.codec.http.HttpResponseStatus.FAILED_DEPENDENCY;
+import static io.netty.handler.codec.http.HttpResponseStatus.FORBIDDEN;
+import static io.netty.handler.codec.http.HttpResponseStatus.GATEWAY_TIMEOUT;
+import static io.netty.handler.codec.http.HttpResponseStatus.GONE;
+import static io.netty.handler.codec.http.HttpResponseStatus.HTTP_VERSION_NOT_SUPPORTED;
+import static io.netty.handler.codec.http.HttpResponseStatus.INSUFFICIENT_STORAGE;
+import static io.netty.handler.codec.http.HttpResponseStatus.INTERNAL_SERVER_ERROR;
+import static io.netty.handler.codec.http.HttpResponseStatus.LENGTH_REQUIRED;
+import static io.netty.handler.codec.http.HttpResponseStatus.LOCKED;
+import static io.netty.handler.codec.http.HttpResponseStatus.METHOD_NOT_ALLOWED;
+import static io.netty.handler.codec.http.HttpResponseStatus.MISDIRECTED_REQUEST;
+import static io.netty.handler.codec.http.HttpResponseStatus.NETWORK_AUTHENTICATION_REQUIRED;
+import static io.netty.handler.codec.http.HttpResponseStatus.NOT_ACCEPTABLE;
+import static io.netty.handler.codec.http.HttpResponseStatus.NOT_EXTENDED;
+import static io.netty.handler.codec.http.HttpResponseStatus.NOT_FOUND;
+import static io.netty.handler.codec.http.HttpResponseStatus.NOT_IMPLEMENTED;
+import static io.netty.handler.codec.http.HttpResponseStatus.OK;
+import static io.netty.handler.codec.http.HttpResponseStatus.PAYMENT_REQUIRED;
+import static io.netty.handler.codec.http.HttpResponseStatus.PRECONDITION_FAILED;
+import static io.netty.handler.codec.http.HttpResponseStatus.PRECONDITION_REQUIRED;
+import static io.netty.handler.codec.http.HttpResponseStatus.PROXY_AUTHENTICATION_REQUIRED;
+import static io.netty.handler.codec.http.HttpResponseStatus.REQUESTED_RANGE_NOT_SATISFIABLE;
+import static io.netty.handler.codec.http.HttpResponseStatus.REQUEST_HEADER_FIELDS_TOO_LARGE;
+import static io.netty.handler.codec.http.HttpResponseStatus.REQUEST_TIMEOUT;
+import static io.netty.handler.codec.http.HttpResponseStatus.REQUEST_URI_TOO_LONG;
+import static io.netty.handler.codec.http.HttpResponseStatus.SERVICE_UNAVAILABLE;
+import static io.netty.handler.codec.http.HttpResponseStatus.TOO_MANY_REQUESTS;
+import static io.netty.handler.codec.http.HttpResponseStatus.UNAUTHORIZED;
+import static io.netty.handler.codec.http.HttpResponseStatus.UNPROCESSABLE_ENTITY;
+import static io.netty.handler.codec.http.HttpResponseStatus.UNSUPPORTED_MEDIA_TYPE;
+import static io.netty.handler.codec.http.HttpResponseStatus.UPGRADE_REQUIRED;
+import static io.netty.handler.codec.http.HttpResponseStatus.VARIANT_ALSO_NEGOTIATES;
+import static io.netty.handler.codec.rtsp.RtspResponseStatuses.REQUEST_ENTITY_TOO_LARGE;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
+import static org.assertj.core.api.Fail.fail;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+/**
+ * Unit tests for the {@link BasicRetryPolicy}
+ */
+class BasicRetryPolicyTest
+{
+ HttpResponse mockResponse;
+ Request mockRequest;
+ RetryPolicy defaultBasicRetryPolicy;
+ Map<String, List<String>> headersMap;
+
+ @BeforeEach
+ void setup()
+ {
+ defaultBasicRetryPolicy = new BasicRetryPolicy();
+ headersMap = new HashMap<>();
+ mockResponse = mock(HttpResponse.class);
+ mockRequest = mock(Request.class);
+ when(mockResponse.headers()).thenReturn(headersMap);
+ when(mockRequest.requestURI()).thenReturn("/api/uri");
+ }
+
+ @ParameterizedTest(name = "{index} => canRetryOnADifferentHost={0}")
+ @ValueSource(booleans = { true, false })
+ void testRetriesWhenThrowableIsProvided(boolean canRetryOnADifferentHost)
+ {
+ IllegalArgumentException throwable = new IllegalArgumentException("Connection Refused");
+ testWithRetries(mockRequest, null, throwable, 3, 100, canRetryOnADifferentHost);
+ }
+
+ @Test
+ void testRetriesOnInternalServerErrorStatusCode()
+ {
+ when(mockResponse.statusCode()).thenReturn(INTERNAL_SERVER_ERROR.code());
+ testWithRetries(mockRequest, mockResponse, null, 5, 200, false);
+ testWithRetries(mockRequest, mockResponse, null, 5, 200, true);
+ }
+
+ @Test
+ void testCompletesWithOKStatusCode() throws ExecutionException, InterruptedException
+ {
+ when(mockResponse.statusCode()).thenReturn(OK.code());
+
+ CompletableFuture<HttpResponse> future = new CompletableFuture<>();
+ defaultBasicRetryPolicy.onResponse(future, mockRequest, mockResponse, null, 1, false,
+ (attempts, retryDelayMillis) -> fail("Should never retry"));
+ future.join();
+ assertThat(future.isDone()).isTrue();
+ assertThat(future.get()).isSameAs(mockResponse);
+ }
+
+ @ParameterizedTest(name = "{index} => canRetryOnADifferentHost={0}")
+ @ValueSource(booleans = { true, false })
+ void testCompletesWithNotFoundStatusCode(boolean canRetryOnADifferentHost)
+ throws ExecutionException, InterruptedException
+ {
+ when(mockResponse.statusCode()).thenReturn(NOT_FOUND.code());
+
+ CompletableFuture<HttpResponse> future = new CompletableFuture<>();
+ if (canRetryOnADifferentHost)
+ {
+ testWithRetries(mockRequest, mockResponse, null, 3, 50, true);
+ }
+ else
+ {
+ defaultBasicRetryPolicy.onResponse(future, mockRequest, mockResponse, null, 1, canRetryOnADifferentHost,
+ (attempts, retryDelayMillis) -> fail("Should never retry"));
+ assertThatExceptionOfType(CompletionException.class)
+ .isThrownBy(future::join)
+ .withCauseInstanceOf(ResourceNotFoundException.class);
+ }
+ }
+
+ @ParameterizedTest(name = "{index} => canRetryOnADifferentHost={0}")
+ @ValueSource(booleans = { true, false })
+ void testRetriesWithNotImplementedStatusCode(boolean canRetryOnADifferentHost)
+ {
+ when(mockResponse.statusCode()).thenReturn(NOT_IMPLEMENTED.code());
+
+ CompletableFuture<HttpResponse> future = new CompletableFuture<>();
+ defaultBasicRetryPolicy.onResponse(future, mockRequest, mockResponse, null, 1, canRetryOnADifferentHost,
+ (attempts, retryDelayMillis) -> fail("Should never retry"));
+
+ assertThatExceptionOfType(CompletionException.class)
+ .isThrownBy(future::join)
+ .withCauseInstanceOf(UnsupportedOperationException.class);
+ assertThat(future.isCompletedExceptionally()).isTrue();
+ }
+
+ @Test
+ void testRetriesWithNotAcceptableStatusCode()
+ {
+ when(mockResponse.statusCode()).thenReturn(NOT_ACCEPTABLE.code());
+ testWithRetries(mockRequest, mockResponse, null, 8, 50, true);
+ }
+
+ @ParameterizedTest(name = "{index} => canRetryOnADifferentHost={0}")
+ @ValueSource(booleans = { true, false })
+ void testRetriesWithServiceUnavailableStatusCode(boolean canRetryOnADifferentHost)
+ {
+ when(mockResponse.statusCode()).thenReturn(SERVICE_UNAVAILABLE.code());
+ testWithRetries(mockRequest, mockResponse, null, 5, 300, canRetryOnADifferentHost);
+ }
+
+ @Test
+ void testRetriesWithServiceUnavailableStatusCodeWithRetryAfterHeader()
+ {
+ when(mockResponse.statusCode()).thenReturn(SERVICE_UNAVAILABLE.code());
+ headersMap.put("Retry-After", Collections.singletonList("5")); // 5 seconds -> 5,000 millis
+ testWithRetries(mockRequest, mockResponse, null, 5, 1000, 5000, false);
+ testWithRetries(mockRequest, mockResponse, null, 5, 1000, 0, true);
+ }
+
+ @Test
+ void testRetriesWithServiceUnavailableStatusCodeWithInvalidRetryAfterHeader()
+ {
+ when(mockResponse.statusCode()).thenReturn(SERVICE_UNAVAILABLE.code());
+ headersMap.put("Retry-After", Collections.singletonList("one-thousand-seconds"));
+ testWithRetries(mockRequest, mockResponse, null, 5, 200, 200, false);
+ testWithRetries(mockRequest, mockResponse, null, 5, 200, 0, true);
+ }
+
+ @Test
+ void testRetriesWithAcceptedStatusCode() throws ExecutionException, InterruptedException
+ {
+ when(mockResponse.statusCode()).thenReturn(ACCEPTED.code());
+ RetryPolicy retryPolicy = new BasicRetryPolicy(1);
+ CompletableFuture<HttpResponse> future = new CompletableFuture<>();
+ AtomicInteger retryActionCalls = new AtomicInteger(0);
+ int maxRetries = 50;
+ for (int currentAttempt = 1; currentAttempt <= maxRetries; currentAttempt++)
+ {
+ retryPolicy.onResponse(future, mockRequest, mockResponse, null, currentAttempt, true,
+ (attempts, retryDelayMillis) -> {
+ retryActionCalls.incrementAndGet();
+ assertThat(attempts).isEqualTo(1);
+ assertThat(retryDelayMillis).isEqualTo(0);
+ });
+ }
+
+ when(mockResponse.statusCode()).thenReturn(OK.code());
+
+ retryPolicy.onResponse(future, mockRequest, mockResponse, null, 1, false,
+ (attempts, retryDelayMillis) -> fail("Should not retry"));
+ future.join();
+ assertThat(future.isDone()).isTrue();
+ assertThat(future.get()).isSameAs(mockResponse);
+ assertThat(retryActionCalls.get()).isEqualTo(maxRetries);
+ }
+
+ private static Stream<Arguments> clientStatusCodeArguments()
+ {
+ return Stream.of(
+ Arguments.of(BAD_REQUEST.code()),
+ Arguments.of(UNAUTHORIZED.code()),
+ Arguments.of(PAYMENT_REQUIRED.code()),
+ Arguments.of(FORBIDDEN.code()),
+ Arguments.of(METHOD_NOT_ALLOWED.code()),
+ Arguments.of(NOT_ACCEPTABLE.code()),
+ Arguments.of(PROXY_AUTHENTICATION_REQUIRED.code()),
+ Arguments.of(REQUEST_TIMEOUT.code()),
+ Arguments.of(CONFLICT.code()),
+ Arguments.of(GONE.code()),
+ Arguments.of(LENGTH_REQUIRED.code()),
+ Arguments.of(PRECONDITION_FAILED.code()),
+ Arguments.of(REQUEST_ENTITY_TOO_LARGE.code()),
+ Arguments.of(REQUEST_URI_TOO_LONG.code()),
+ Arguments.of(UNSUPPORTED_MEDIA_TYPE.code()),
+ Arguments.of(REQUESTED_RANGE_NOT_SATISFIABLE.code()),
+ Arguments.of(EXPECTATION_FAILED.code()),
+ Arguments.of(MISDIRECTED_REQUEST.code()),
+ Arguments.of(UNPROCESSABLE_ENTITY.code()),
+ Arguments.of(LOCKED.code()),
+ Arguments.of(FAILED_DEPENDENCY.code()),
+ Arguments.of(UPGRADE_REQUIRED.code()),
+ Arguments.of(PRECONDITION_REQUIRED.code()),
+ Arguments.of(TOO_MANY_REQUESTS.code()),
+ Arguments.of(REQUEST_HEADER_FIELDS_TOO_LARGE.code())
+ );
+ }
+
+ @ParameterizedTest(name = "{index} => statusCode={0}")
+ @MethodSource("clientStatusCodeArguments")
+ void testRetriesWithClientError(int statusCode)
+ {
+ when(mockResponse.statusCode()).thenReturn(statusCode);
+ testWithRetries(mockRequest, mockResponse, null, 2, 200, 200, false, false);
+ testWithRetries(mockRequest, mockResponse, null, 2, 200, 0, true, false);
+ }
+
+ private static Stream<Arguments> serverStatusCodeArguments()
Review Comment:
same for serve error, `5xx`
##########
common/src/main/java/org/apache/cassandra/sidecar/common/data/GossipInfoResponse.java:
##########
@@ -0,0 +1,292 @@
+/*
+ * 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.sidecar.common.data;
+
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+
+import static org.apache.cassandra.sidecar.common.data.GossipInfoResponse.GossipField.DC;
+import static org.apache.cassandra.sidecar.common.data.GossipInfoResponse.GossipField.DISK_USAGE;
+import static org.apache.cassandra.sidecar.common.data.GossipInfoResponse.GossipField.GENERATION;
+import static org.apache.cassandra.sidecar.common.data.GossipInfoResponse.GossipField.HEARTBEAT;
+import static org.apache.cassandra.sidecar.common.data.GossipInfoResponse.GossipField.HOST_ID;
+import static org.apache.cassandra.sidecar.common.data.GossipInfoResponse.GossipField.INTERNAL_ADDRESS_AND_PORT;
+import static org.apache.cassandra.sidecar.common.data.GossipInfoResponse.GossipField.INTERNAL_IP;
+import static org.apache.cassandra.sidecar.common.data.GossipInfoResponse.GossipField.LOAD;
+import static org.apache.cassandra.sidecar.common.data.GossipInfoResponse.GossipField.NATIVE_ADDRESS_AND_PORT;
+import static org.apache.cassandra.sidecar.common.data.GossipInfoResponse.GossipField.NET_VERSION;
+import static org.apache.cassandra.sidecar.common.data.GossipInfoResponse.GossipField.RACK;
+import static org.apache.cassandra.sidecar.common.data.GossipInfoResponse.GossipField.RELEASE_VERSION;
+import static org.apache.cassandra.sidecar.common.data.GossipInfoResponse.GossipField.REMOVAL_COORDINATOR;
+import static org.apache.cassandra.sidecar.common.data.GossipInfoResponse.GossipField.RPC_ADDRESS;
+import static org.apache.cassandra.sidecar.common.data.GossipInfoResponse.GossipField.RPC_READY;
+import static org.apache.cassandra.sidecar.common.data.GossipInfoResponse.GossipField.SCHEMA;
+import static org.apache.cassandra.sidecar.common.data.GossipInfoResponse.GossipField.SEVERITY;
+import static org.apache.cassandra.sidecar.common.data.GossipInfoResponse.GossipField.SSTABLE_VERSIONS;
+import static org.apache.cassandra.sidecar.common.data.GossipInfoResponse.GossipField.STATUS;
+import static org.apache.cassandra.sidecar.common.data.GossipInfoResponse.GossipField.STATUS_WITH_PORT;
+import static org.apache.cassandra.sidecar.common.data.GossipInfoResponse.GossipField.TOKENS;
+import static org.apache.cassandra.sidecar.common.data.GossipInfoResponse.GossipField.read;
+
+/**
+ * A class representing the response of the cassandra gossip endpoint
+ */
+public class GossipInfoResponse extends HashMap<String, GossipInfoResponse.GossipInfo>
+{
+ /**
+ * Data accessor for reading Gossip states
+ */
+ public static class GossipInfo extends HashMap<String, String>
+ {
+ /**
+ * Converts the key, if it is using the UPPER UNDERSCORE format, into camel case.
+ * Then, put the new key and value.
+ *
+ * @param snakeCaseKey the key to convert
+ * @param value the value for the gossip info entry
+ */
+ public void camelizeKeyAndPut(String snakeCaseKey, String value)
+ {
+ String key = toLowerCamelCase(snakeCaseKey.toUpperCase());
+ super.put(key, value);
+ }
Review Comment:
How do you make sure the input `String snakeCaseKey` is indeed in snake case. I would suggest to convert the value into enum `GossipField` first by looking up using `valueOf()`, and relocate the `toLowerCamelCase()` to the enum, which simplifies the implementation a bit, since validation for null or empty is no longer required.
```java
// in protected enum GossipField
String toLowerCamelCase()
{
String upperUnderscoreCase = name();
StringBuilder sb = new StringBuilder(upperUnderscoreCase.length());
sb.append(Character.toLowerCase(upperUnderscoreCase.charAt(0)));
int length = upperUnderscoreCase.length();
for (int i = 1; i < length; i++)
{
if (upperUnderscoreCase.charAt(i) == '_' && i + 1 < length)
{
i++;
sb.append(upperUnderscoreCase.charAt(i));
}
else
{
sb.append(Character.toLowerCase(upperUnderscoreCase.charAt(i)));
}
}
return sb.toString();
}
```
##########
client/src/test/java/org/apache/cassandra/sidecar/client/retry/BasicRetryPolicyTest.java:
##########
@@ -0,0 +1,376 @@
+/*
+ * 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.sidecar.client.retry;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CompletionException;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.stream.Stream;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.junit.jupiter.params.provider.ValueSource;
+
+import org.apache.cassandra.sidecar.client.HttpResponse;
+import org.apache.cassandra.sidecar.client.exception.ResourceNotFoundException;
+import org.apache.cassandra.sidecar.client.exception.RetriesExhaustedException;
+import org.apache.cassandra.sidecar.client.exception.UnexpectedStatusCodeException;
+import org.apache.cassandra.sidecar.client.request.Request;
+
+import static io.netty.handler.codec.http.HttpResponseStatus.ACCEPTED;
+import static io.netty.handler.codec.http.HttpResponseStatus.BAD_GATEWAY;
+import static io.netty.handler.codec.http.HttpResponseStatus.BAD_REQUEST;
+import static io.netty.handler.codec.http.HttpResponseStatus.CONFLICT;
+import static io.netty.handler.codec.http.HttpResponseStatus.EXPECTATION_FAILED;
+import static io.netty.handler.codec.http.HttpResponseStatus.FAILED_DEPENDENCY;
+import static io.netty.handler.codec.http.HttpResponseStatus.FORBIDDEN;
+import static io.netty.handler.codec.http.HttpResponseStatus.GATEWAY_TIMEOUT;
+import static io.netty.handler.codec.http.HttpResponseStatus.GONE;
+import static io.netty.handler.codec.http.HttpResponseStatus.HTTP_VERSION_NOT_SUPPORTED;
+import static io.netty.handler.codec.http.HttpResponseStatus.INSUFFICIENT_STORAGE;
+import static io.netty.handler.codec.http.HttpResponseStatus.INTERNAL_SERVER_ERROR;
+import static io.netty.handler.codec.http.HttpResponseStatus.LENGTH_REQUIRED;
+import static io.netty.handler.codec.http.HttpResponseStatus.LOCKED;
+import static io.netty.handler.codec.http.HttpResponseStatus.METHOD_NOT_ALLOWED;
+import static io.netty.handler.codec.http.HttpResponseStatus.MISDIRECTED_REQUEST;
+import static io.netty.handler.codec.http.HttpResponseStatus.NETWORK_AUTHENTICATION_REQUIRED;
+import static io.netty.handler.codec.http.HttpResponseStatus.NOT_ACCEPTABLE;
+import static io.netty.handler.codec.http.HttpResponseStatus.NOT_EXTENDED;
+import static io.netty.handler.codec.http.HttpResponseStatus.NOT_FOUND;
+import static io.netty.handler.codec.http.HttpResponseStatus.NOT_IMPLEMENTED;
+import static io.netty.handler.codec.http.HttpResponseStatus.OK;
+import static io.netty.handler.codec.http.HttpResponseStatus.PAYMENT_REQUIRED;
+import static io.netty.handler.codec.http.HttpResponseStatus.PRECONDITION_FAILED;
+import static io.netty.handler.codec.http.HttpResponseStatus.PRECONDITION_REQUIRED;
+import static io.netty.handler.codec.http.HttpResponseStatus.PROXY_AUTHENTICATION_REQUIRED;
+import static io.netty.handler.codec.http.HttpResponseStatus.REQUESTED_RANGE_NOT_SATISFIABLE;
+import static io.netty.handler.codec.http.HttpResponseStatus.REQUEST_HEADER_FIELDS_TOO_LARGE;
+import static io.netty.handler.codec.http.HttpResponseStatus.REQUEST_TIMEOUT;
+import static io.netty.handler.codec.http.HttpResponseStatus.REQUEST_URI_TOO_LONG;
+import static io.netty.handler.codec.http.HttpResponseStatus.SERVICE_UNAVAILABLE;
+import static io.netty.handler.codec.http.HttpResponseStatus.TOO_MANY_REQUESTS;
+import static io.netty.handler.codec.http.HttpResponseStatus.UNAUTHORIZED;
+import static io.netty.handler.codec.http.HttpResponseStatus.UNPROCESSABLE_ENTITY;
+import static io.netty.handler.codec.http.HttpResponseStatus.UNSUPPORTED_MEDIA_TYPE;
+import static io.netty.handler.codec.http.HttpResponseStatus.UPGRADE_REQUIRED;
+import static io.netty.handler.codec.http.HttpResponseStatus.VARIANT_ALSO_NEGOTIATES;
+import static io.netty.handler.codec.rtsp.RtspResponseStatuses.REQUEST_ENTITY_TOO_LARGE;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
+import static org.assertj.core.api.Fail.fail;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+/**
+ * Unit tests for the {@link BasicRetryPolicy}
+ */
+class BasicRetryPolicyTest
+{
+ HttpResponse mockResponse;
+ Request mockRequest;
+ RetryPolicy defaultBasicRetryPolicy;
+ Map<String, List<String>> headersMap;
+
+ @BeforeEach
+ void setup()
+ {
+ defaultBasicRetryPolicy = new BasicRetryPolicy();
+ headersMap = new HashMap<>();
+ mockResponse = mock(HttpResponse.class);
+ mockRequest = mock(Request.class);
+ when(mockResponse.headers()).thenReturn(headersMap);
+ when(mockRequest.requestURI()).thenReturn("/api/uri");
+ }
+
+ @ParameterizedTest(name = "{index} => canRetryOnADifferentHost={0}")
+ @ValueSource(booleans = { true, false })
+ void testRetriesWhenThrowableIsProvided(boolean canRetryOnADifferentHost)
+ {
+ IllegalArgumentException throwable = new IllegalArgumentException("Connection Refused");
+ testWithRetries(mockRequest, null, throwable, 3, 100, canRetryOnADifferentHost);
+ }
+
+ @Test
+ void testRetriesOnInternalServerErrorStatusCode()
+ {
+ when(mockResponse.statusCode()).thenReturn(INTERNAL_SERVER_ERROR.code());
+ testWithRetries(mockRequest, mockResponse, null, 5, 200, false);
+ testWithRetries(mockRequest, mockResponse, null, 5, 200, true);
+ }
+
+ @Test
+ void testCompletesWithOKStatusCode() throws ExecutionException, InterruptedException
+ {
+ when(mockResponse.statusCode()).thenReturn(OK.code());
+
+ CompletableFuture<HttpResponse> future = new CompletableFuture<>();
+ defaultBasicRetryPolicy.onResponse(future, mockRequest, mockResponse, null, 1, false,
+ (attempts, retryDelayMillis) -> fail("Should never retry"));
+ future.join();
+ assertThat(future.isDone()).isTrue();
+ assertThat(future.get()).isSameAs(mockResponse);
+ }
+
+ @ParameterizedTest(name = "{index} => canRetryOnADifferentHost={0}")
+ @ValueSource(booleans = { true, false })
+ void testCompletesWithNotFoundStatusCode(boolean canRetryOnADifferentHost)
+ throws ExecutionException, InterruptedException
+ {
+ when(mockResponse.statusCode()).thenReturn(NOT_FOUND.code());
+
+ CompletableFuture<HttpResponse> future = new CompletableFuture<>();
+ if (canRetryOnADifferentHost)
+ {
+ testWithRetries(mockRequest, mockResponse, null, 3, 50, true);
+ }
+ else
+ {
+ defaultBasicRetryPolicy.onResponse(future, mockRequest, mockResponse, null, 1, canRetryOnADifferentHost,
+ (attempts, retryDelayMillis) -> fail("Should never retry"));
+ assertThatExceptionOfType(CompletionException.class)
+ .isThrownBy(future::join)
+ .withCauseInstanceOf(ResourceNotFoundException.class);
+ }
+ }
+
+ @ParameterizedTest(name = "{index} => canRetryOnADifferentHost={0}")
+ @ValueSource(booleans = { true, false })
+ void testRetriesWithNotImplementedStatusCode(boolean canRetryOnADifferentHost)
+ {
+ when(mockResponse.statusCode()).thenReturn(NOT_IMPLEMENTED.code());
+
+ CompletableFuture<HttpResponse> future = new CompletableFuture<>();
+ defaultBasicRetryPolicy.onResponse(future, mockRequest, mockResponse, null, 1, canRetryOnADifferentHost,
+ (attempts, retryDelayMillis) -> fail("Should never retry"));
+
+ assertThatExceptionOfType(CompletionException.class)
+ .isThrownBy(future::join)
+ .withCauseInstanceOf(UnsupportedOperationException.class);
+ assertThat(future.isCompletedExceptionally()).isTrue();
+ }
+
+ @Test
+ void testRetriesWithNotAcceptableStatusCode()
+ {
+ when(mockResponse.statusCode()).thenReturn(NOT_ACCEPTABLE.code());
+ testWithRetries(mockRequest, mockResponse, null, 8, 50, true);
+ }
+
+ @ParameterizedTest(name = "{index} => canRetryOnADifferentHost={0}")
+ @ValueSource(booleans = { true, false })
+ void testRetriesWithServiceUnavailableStatusCode(boolean canRetryOnADifferentHost)
+ {
+ when(mockResponse.statusCode()).thenReturn(SERVICE_UNAVAILABLE.code());
+ testWithRetries(mockRequest, mockResponse, null, 5, 300, canRetryOnADifferentHost);
+ }
+
+ @Test
+ void testRetriesWithServiceUnavailableStatusCodeWithRetryAfterHeader()
+ {
+ when(mockResponse.statusCode()).thenReturn(SERVICE_UNAVAILABLE.code());
+ headersMap.put("Retry-After", Collections.singletonList("5")); // 5 seconds -> 5,000 millis
+ testWithRetries(mockRequest, mockResponse, null, 5, 1000, 5000, false);
+ testWithRetries(mockRequest, mockResponse, null, 5, 1000, 0, true);
+ }
+
+ @Test
+ void testRetriesWithServiceUnavailableStatusCodeWithInvalidRetryAfterHeader()
+ {
+ when(mockResponse.statusCode()).thenReturn(SERVICE_UNAVAILABLE.code());
+ headersMap.put("Retry-After", Collections.singletonList("one-thousand-seconds"));
+ testWithRetries(mockRequest, mockResponse, null, 5, 200, 200, false);
+ testWithRetries(mockRequest, mockResponse, null, 5, 200, 0, true);
+ }
+
+ @Test
+ void testRetriesWithAcceptedStatusCode() throws ExecutionException, InterruptedException
+ {
+ when(mockResponse.statusCode()).thenReturn(ACCEPTED.code());
+ RetryPolicy retryPolicy = new BasicRetryPolicy(1);
+ CompletableFuture<HttpResponse> future = new CompletableFuture<>();
+ AtomicInteger retryActionCalls = new AtomicInteger(0);
+ int maxRetries = 50;
+ for (int currentAttempt = 1; currentAttempt <= maxRetries; currentAttempt++)
+ {
+ retryPolicy.onResponse(future, mockRequest, mockResponse, null, currentAttempt, true,
+ (attempts, retryDelayMillis) -> {
+ retryActionCalls.incrementAndGet();
+ assertThat(attempts).isEqualTo(1);
+ assertThat(retryDelayMillis).isEqualTo(0);
+ });
+ }
+
+ when(mockResponse.statusCode()).thenReturn(OK.code());
+
+ retryPolicy.onResponse(future, mockRequest, mockResponse, null, 1, false,
+ (attempts, retryDelayMillis) -> fail("Should not retry"));
+ future.join();
+ assertThat(future.isDone()).isTrue();
+ assertThat(future.get()).isSameAs(mockResponse);
+ assertThat(retryActionCalls.get()).isEqualTo(maxRetries);
+ }
+
+ private static Stream<Arguments> clientStatusCodeArguments()
Review Comment:
nit: All `4XX` are client error. The stream returned is not the complete set. The original implementation only returns the established client error codes, which is a subset. That being said, it is rarely a good idea to have custom status code. I only suggest to cover all 4XX code from the perspective of testing, because all of them technically represent client errors, regardless of the predefined or the custom.
```suggestion
private static Stream<Arguments> clientStatusCodeArguments()
{
return IntStream.range(400, 500).boxed().map(Arguments::of);
}
```
--
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-sidecar] frankgh commented on a diff in pull request #45: CEP-28: Implement Bulk API endpoints and introduce the Sidecar Client to Support Bulk Analytics
Posted by "frankgh (via GitHub)" <gi...@apache.org>.
frankgh commented on code in PR #45:
URL: https://github.com/apache/cassandra-sidecar/pull/45#discussion_r1194297309
##########
client/src/main/java/org/apache/cassandra/sidecar/client/exception/UnexpectedStatusCodeException.java:
##########
@@ -0,0 +1,53 @@
+/*
+ * 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.sidecar.client.exception;
+
+/**
+ * Represents an exception raised when an unexpected status code is encountered
+ */
+public class UnexpectedStatusCodeException extends RuntimeException
+{
+ /**
+ * Constructs a new {@link UnexpectedStatusCodeException} with the given {@code statusCode} and {@code body}
+ *
+ * @param statusCode the response status code
+ * @param body the body of the response
+ */
+ public UnexpectedStatusCodeException(int statusCode, String body)
Review Comment:
this constructor is called from
```
UnexpectedStatusCodeException unexpectedStatusCode(HttpResponse response)
{
return new UnexpectedStatusCodeException(response.statusCode(), response.contentAsString());
}
```
and `response.contentAsString()` is a best effort attempt to convert the raw response to a UTF-8 String,
--
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-sidecar] frankgh commented on a diff in pull request #45: CEP-28: Implement Bulk API endpoints and introduce the Sidecar Client to Support Bulk Analytics
Posted by "frankgh (via GitHub)" <gi...@apache.org>.
frankgh commented on code in PR #45:
URL: https://github.com/apache/cassandra-sidecar/pull/45#discussion_r1194375762
##########
src/test/resources/sidecar_with_single_multiple_instances.yaml:
##########
@@ -38,6 +38,8 @@ sidecar:
- stream_requests_per_sec: 5000
- delay_sec: 5
- timeout_sec: 10
+ - allowable_time_skew_in_minutes: 60
Review Comment:
discussed offline. we decided to leave the value as is for 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.
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-sidecar] yifan-c commented on a diff in pull request #45: CEP-28: Implement Bulk API endpoints and introduce the Sidecar Client to Support Bulk Analytics
Posted by "yifan-c (via GitHub)" <gi...@apache.org>.
yifan-c commented on code in PR #45:
URL: https://github.com/apache/cassandra-sidecar/pull/45#discussion_r1194431202
##########
common/src/main/java/org/apache/cassandra/sidecar/common/CassandraAdapterDelegate.java:
##########
@@ -145,47 +124,73 @@ private void healthCheckInternal()
Row oneResult = activeSession.execute("select release_version, partitioner from system.local")
.one();
- String releaseVersion = oneResult.getString("release_version");
- // update the nodeSettings cache.
// Note that within the scope of this method, we should keep on using the local releaseVersion
- nodeSettings = new NodeSettings(releaseVersion, oneResult.getString("partitioner"));
- // this might swap the adapter out
- SimpleCassandraVersion newVersion = SimpleCassandraVersion.create(releaseVersion);
- if (!newVersion.equals(currentVersion))
+ String releaseVersion = oneResult.getString("release_version");
+ NodeSettings newNodeSettings = new NodeSettings(releaseVersion, oneResult.getString("partitioner"));
+ if (!newNodeSettings.equals(nodeSettings))
{
- currentVersion = newVersion;
- adapter = versionProvider.getCassandra(nodeSettings.releaseVersion()).create(cqlSession, jmxClient);
- logger.info("Cassandra version change detected. New adapter loaded: {}", adapter);
+ // update the nodeSettings cache.
+ SimpleCassandraVersion previousVersion = currentVersion;
+ currentVersion = SimpleCassandraVersion.create(releaseVersion);
+ adapter = versionProvider.cassandra(releaseVersion)
+ .create(cqlSessionProvider, jmxClient);
+ nodeSettings = newNodeSettings;
Review Comment:
yep
--
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-sidecar] yifan-c commented on a diff in pull request #45: CEP-28: Implement Bulk API endpoints and introduce the Sidecar Client to Support Bulk Analytics
Posted by "yifan-c (via GitHub)" <gi...@apache.org>.
yifan-c commented on code in PR #45:
URL: https://github.com/apache/cassandra-sidecar/pull/45#discussion_r1191767794
##########
src/test/java/org/apache/cassandra/sidecar/routes/sstableuploads/BaseUploadsHandlerTest.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.sidecar.routes.sstableuploads;
+
+import java.io.File;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.UUID;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.stream.Stream;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.io.TempDir;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.datastax.driver.core.KeyspaceMetadata;
+import com.datastax.driver.core.Metadata;
+import com.datastax.driver.core.TableMetadata;
+import com.google.inject.AbstractModule;
+import com.google.inject.Guice;
+import com.google.inject.Injector;
+import com.google.inject.Provides;
+import com.google.inject.Singleton;
+import com.google.inject.util.Modules;
+import io.vertx.core.Vertx;
+import io.vertx.core.http.HttpServer;
+import io.vertx.ext.web.client.WebClient;
+import io.vertx.junit5.VertxTestContext;
+import org.apache.cassandra.sidecar.Configuration;
+import org.apache.cassandra.sidecar.MainModule;
+import org.apache.cassandra.sidecar.TestModule;
+import org.apache.cassandra.sidecar.cluster.InstancesConfig;
+import org.apache.cassandra.sidecar.common.CassandraAdapterDelegate;
+import org.apache.cassandra.sidecar.config.CacheConfiguration;
+import org.apache.cassandra.sidecar.config.WorkerPoolConfiguration;
+import org.apache.cassandra.sidecar.snapshots.SnapshotUtils;
+
+import static org.apache.cassandra.sidecar.snapshots.SnapshotUtils.mockInstancesConfig;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+/**
+ * Common functionality for the SSTable Uploads {@link SSTableUploadHandler}, {@link SSTableImportHandler},
+ * and {@link SSTableCleanupHandler} tests.
+ */
+class BaseUploadsHandlerTest
+{
+ protected final Logger logger = LoggerFactory.getLogger(this.getClass());
Review Comment:
The `logger` is not `static`.
--
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