JeetKunDoug commented on code in PR #80:
URL: 
https://github.com/apache/cassandra-analytics/pull/80#discussion_r1757195386


##########
cassandra-analytics-core/src/main/java/org/apache/cassandra/spark/bulkwriter/coordinatedwrite/MultiClusterInfoProvider.java:
##########
@@ -0,0 +1,45 @@
+/*
+ * 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.spark.bulkwriter.coordinatedwrite;
+
+import java.util.List;
+
+import org.apache.cassandra.spark.bulkwriter.ClusterInfo;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+
+/**
+ * Provider for multiple ClusterInfo and lookup
+ */
+public interface MultiClusterInfoProvider

Review Comment:
   NIT: this is just `MultiClusterInfo` like the previous PR - no need for 
`Provider` in the interface name.



##########
cassandra-analytics-core/src/main/java/org/apache/cassandra/spark/bulkwriter/coordinatedwrite/CassandraClusterInfoGroup.java:
##########
@@ -0,0 +1,278 @@
+/*
+ * 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.spark.bulkwriter.coordinatedwrite;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.EnumSet;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.function.Consumer;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+
+import com.google.common.base.Preconditions;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import o.a.c.sidecar.client.shaded.common.response.TimeSkewResponse;
+import org.apache.cassandra.bridge.CassandraVersionFeatures;
+import org.apache.cassandra.spark.bulkwriter.CassandraContext;
+import org.apache.cassandra.spark.bulkwriter.ClusterInfo;
+import org.apache.cassandra.spark.bulkwriter.WriteAvailability;
+import org.apache.cassandra.spark.bulkwriter.RingInstance;
+import org.apache.cassandra.spark.bulkwriter.token.TokenRangeMapping;
+import org.apache.cassandra.spark.data.ReplicationFactor;
+import org.apache.cassandra.spark.data.partitioner.Partitioner;
+import org.apache.cassandra.spark.utils.MapUtils;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+
+public class CassandraClusterInfoGroup implements ClusterInfo, 
MultiClusterInfoProvider
+{
+    private static final Logger LOGGER = 
LoggerFactory.getLogger(CassandraClusterInfoGroup.class);
+
+    private static final long serialVersionUID = 5337884321245616172L;
+
+    // immutable
+    private final List<ClusterInfo> clusterInfos;
+    private final Map<String, ClusterInfo> clusterInfoById;
+    // map key might be stale, e.g. instance is removed from cluster, but it 
remains in the map. In such case, we do not expect call-sites use the stale key
+    private final Map<RingInstance, String> instanceToClusterMap = new 
HashMap<>();
+
+    public CassandraClusterInfoGroup(List<ClusterInfo> clusterInfos)
+    {
+        Preconditions.checkArgument(clusterInfos != null && 
!clusterInfos.isEmpty(),
+                                    "clusterInfos cannot be null or empty");
+        this.clusterInfos = Collections.unmodifiableList(clusterInfos);
+        this.clusterInfoById = 
clusterInfos.stream().collect(Collectors.toMap(ClusterInfo::clusterId, 
Function.identity()));
+    }
+
+    @Override
+    public void refreshClusterInfo()
+    {
+        runOnEach(ClusterInfo::refreshClusterInfo);
+    }
+
+    @Override
+    public TokenRangeMapping<RingInstance> getTokenRangeMapping(boolean cached)
+    {
+        if (clusterInfos.size() == 1)
+        {
+            return clusterInfos.get(0).getTokenRangeMapping(cached);
+        }
+
+        Map<String, TokenRangeMapping<RingInstance>> aggregated = 
applyOnEach(c -> c.getTokenRangeMapping(cached));
+        // When there are multiple clusters, populate the reverse lookup map 
when fetching latest or initializing
+        if (!cached || aggregated.isEmpty())
+        {
+            // todo: synchronize and clear the reverse lookup map?
+            instanceToClusterMap.clear();
+            aggregated.forEach((clusterId, mapping) -> mapping.getTokenRanges()
+                                                              .keySet()
+                                                              
.forEach(instance -> instanceToClusterMap.put(instance, clusterId)));
+        }
+
+        return TokenRangeMapping.consolidate(new 
ArrayList<>(aggregated.values()));
+    }
+
+    /**
+     * @return the lowest cassandra version among all clusters
+     */
+    @Override
+    public String getLowestCassandraVersion()
+    {
+        if (clusterInfos.size() == 1)
+        {
+            return clusterInfos.get(0).getLowestCassandraVersion();
+        }
+
+        Map<String, String> aggregated = 
applyOnEach(ClusterInfo::getLowestCassandraVersion);
+        List<CassandraVersionFeatures> versions = aggregated.values()
+                                                            .stream()
+                                                            
.map(CassandraVersionFeatures::cassandraVersionFeaturesFromCassandraVersion)
+                                                            .sorted()
+                                                            
.collect(Collectors.toList());
+        CassandraVersionFeatures first = versions.get(0);
+        CassandraVersionFeatures last = versions.get(versions.size() - 1);
+        int majorDiff = Math.abs(first.getMajorVersion() - 
last.getMajorVersion());
+        if (majorDiff >= 1)
+        {
+            throw new IllegalStateException("Cluster versions are not 
compatible. " +
+                                            "lowest=" + 
first.getRawVersionString() +
+                                            " and highest=" + 
last.getRawVersionString());
+        }
+
+        return first.getRawVersionString();
+    }
+
+    @Override
+    public Map<RingInstance, WriteAvailability> clusterWriteAvailability()
+    {
+        if (clusterInfos.size() == 1)
+        {
+            return clusterInfos.get(0).clusterWriteAvailability();
+        }
+
+        Map<String, Map<RingInstance, WriteAvailability>> aggregated = 
applyOnEach(ClusterInfo::clusterWriteAvailability);
+        Map<RingInstance, WriteAvailability> consolidated = new HashMap<>();
+        aggregated.values().forEach(consolidated::putAll);
+        return consolidated;
+    }
+
+    @Override
+    public Partitioner getPartitioner()
+    {
+        Map<String, Partitioner> aggregated = 
applyOnEach(ClusterInfo::getPartitioner);
+        Set<Partitioner> partitioners = EnumSet.copyOf(aggregated.values());
+        if (partitioners.size() != 1)
+        {
+            throw new IllegalStateException("Clusters are not running with the 
same partitioner kind. Found partitioners: " + aggregated);
+        }
+
+        return MapUtils.firstEntry(aggregated).getValue();

Review Comment:
   ```suggestion
           return aggregated.get(clusterInfos.get(0).clusterId());
   ```



##########
cassandra-analytics-core/src/main/java/org/apache/cassandra/spark/bulkwriter/coordinatedwrite/CassandraClusterInfoGroup.java:
##########
@@ -0,0 +1,300 @@
+/*
+ * 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.spark.bulkwriter.coordinatedwrite;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.EnumSet;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.function.Consumer;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+
+import com.google.common.base.Preconditions;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import o.a.c.sidecar.client.shaded.common.response.TimeSkewResponse;
+import org.apache.cassandra.bridge.CassandraVersionFeatures;
+import org.apache.cassandra.spark.bulkwriter.CassandraContext;
+import org.apache.cassandra.spark.bulkwriter.ClusterInfo;
+import org.apache.cassandra.spark.bulkwriter.WriteAvailability;
+import org.apache.cassandra.spark.bulkwriter.RingInstance;
+import org.apache.cassandra.spark.bulkwriter.token.TokenRangeMapping;
+import org.apache.cassandra.spark.data.ReplicationFactor;
+import org.apache.cassandra.spark.data.partitioner.Partitioner;
+import org.apache.cassandra.spark.utils.MapUtils;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+
+public class CassandraClusterInfoGroup implements ClusterInfo, 
MultiClusterInfoProvider
+{
+    private static final Logger LOGGER = 
LoggerFactory.getLogger(CassandraClusterInfoGroup.class);
+
+    private static final long serialVersionUID = 5337884321245616172L;
+
+    // immutable
+    private final List<ClusterInfo> clusterInfos;
+    private transient volatile Map<String, ClusterInfo> clusterInfoById;
+    private transient volatile TokenRangeMapping<RingInstance> 
consolidatedTokenRangeMapping;
+
+    public CassandraClusterInfoGroup(List<ClusterInfo> clusterInfos)
+    {
+        Preconditions.checkArgument(clusterInfos != null && 
!clusterInfos.isEmpty(),
+                                    "clusterInfos cannot be null or empty");
+        this.clusterInfos = Collections.unmodifiableList(clusterInfos);
+        buildClusterInfoById();
+    }
+
+    @Override
+    public void refreshClusterInfo()
+    {
+        runOnEach(ClusterInfo::refreshClusterInfo);
+    }
+
+    @Override
+    public TokenRangeMapping<RingInstance> getTokenRangeMapping(boolean cached)
+    {
+        if (clusterInfos.size() == 1)
+        {
+            return clusterInfos.get(0).getTokenRangeMapping(cached);
+        }
+
+        if (!cached || consolidatedTokenRangeMapping == null)
+        {
+            synchronized (this)
+            {
+                // return immediately if consolidatedTokenRangeMapping has 
been initialized and call-site asks for the cached value
+                if (cached && consolidatedTokenRangeMapping != null)
+                {
+                    return consolidatedTokenRangeMapping;
+                }
+                Map<String, TokenRangeMapping<RingInstance>> aggregated = 
applyOnEach(c -> c.getTokenRangeMapping(cached));
+                consolidatedTokenRangeMapping = 
TokenRangeMapping.consolidate(new ArrayList<>(aggregated.values()));
+            }
+        }
+
+        return consolidatedTokenRangeMapping;
+    }
+
+    /**
+     * @return the lowest cassandra version among all clusters
+     */
+    @Override
+    public String getLowestCassandraVersion()
+    {
+        if (clusterInfos.size() == 1)
+        {
+            return clusterInfos.get(0).getLowestCassandraVersion();
+        }
+
+        Map<String, String> aggregated = 
applyOnEach(ClusterInfo::getLowestCassandraVersion);
+        List<CassandraVersionFeatures> versions = aggregated.values()
+                                                            .stream()
+                                                            
.map(CassandraVersionFeatures::cassandraVersionFeaturesFromCassandraVersion)
+                                                            .sorted()
+                                                            
.collect(Collectors.toList());
+        CassandraVersionFeatures first = versions.get(0);
+        CassandraVersionFeatures last = versions.get(versions.size() - 1);
+        int majorDiff = Math.abs(first.getMajorVersion() - 
last.getMajorVersion());
+        if (majorDiff >= 1)
+        {
+            throw new IllegalStateException("Cluster versions are not 
compatible. " +
+                                            "lowest=" + 
first.getRawVersionString() +
+                                            " and highest=" + 
last.getRawVersionString());
+        }
+
+        return first.getRawVersionString();
+    }
+
+    @Override
+    public Map<RingInstance, WriteAvailability> clusterWriteAvailability()
+    {
+        if (clusterInfos.size() == 1)
+        {
+            return clusterInfos.get(0).clusterWriteAvailability();
+        }
+
+        Map<String, Map<RingInstance, WriteAvailability>> aggregated = 
applyOnEach(ClusterInfo::clusterWriteAvailability);
+        Map<RingInstance, WriteAvailability> consolidated = new HashMap<>();
+        aggregated.values().forEach(consolidated::putAll);
+        return consolidated;
+    }
+
+    @Override
+    public Partitioner getPartitioner()
+    {
+        Map<String, Partitioner> aggregated = 
applyOnEach(ClusterInfo::getPartitioner);
+        Set<Partitioner> partitioners = EnumSet.copyOf(aggregated.values());
+        if (partitioners.size() != 1)
+        {
+            throw new IllegalStateException("Clusters are not running with the 
same partitioner kind. Found partitioners: " + aggregated);
+        }
+
+        return MapUtils.firstEntry(aggregated).getValue();
+    }
+
+    @Override
+    public void checkBulkWriterIsEnabledOrThrow()
+    {
+        runOnEach(ClusterInfo::checkBulkWriterIsEnabledOrThrow);
+    }
+
+    /**
+     * @return the largest time skew retrieved from the target replicas
+     */
+    @Override
+    public TimeSkewResponse getTimeSkew(List<RingInstance> instances)
+    {
+        if (clusterInfos.size() == 1)
+        {
+            return clusterInfos.get(0).getTimeSkew(instances);
+        }
+
+        Map<String, List<RingInstance>> instancesByClusterId = 
instances.stream().collect(Collectors.groupingBy(instance -> {
+            String clusterId = instance.clusterId();
+            Preconditions.checkState(clusterId != null,
+                                     "RingInstance must define its clusterId 
for coordinated write");
+            return clusterId;
+        }));
+        long localNow = System.currentTimeMillis();
+        long maxDiff = 0;
+        TimeSkewResponse largestSkew = null;
+        for (Map.Entry<String, List<RingInstance>> entry : 
instancesByClusterId.entrySet())
+        {
+            String clusterId = entry.getKey();
+            List<RingInstance> instancesOfCluster = entry.getValue();
+            ClusterInfo clusterInfo = cluster(clusterId);
+            Preconditions.checkState(clusterInfo != null, "ClusterInfo not 
found with clusterId: " + clusterId);
+            TimeSkewResponse response = 
clusterInfo.getTimeSkew(instancesOfCluster);
+            long d = Math.abs(response.currentTime - localNow);
+            if (Math.abs(response.currentTime - localNow) > maxDiff)
+            {
+                maxDiff = d;
+                largestSkew = response;
+            }
+        }
+        return largestSkew;
+    }

Review Comment:
   If we add an `allInstances` method to `clusterInfo` this becomes _much 
simpler_:
   ```suggestion
       public TimeSkewResponse getTimeSkew(List<RingInstance> instances)
       {
           return applyOnEach(clusterInfo ->
                              
clusterInfo.getTimeSkew(clusterInfo.allInstances()))
                  .values()
                  .stream()
                  .max(Comparator.comparingLong(tsr -> Math.abs(tsr.currentTime 
- System.currentTimeMillis())))
                  .orElseThrow(() -> new RuntimeException("Could not load time 
skew data from any cluster."));
       }
   ```
   
   I'd say the overhead of the `applyOnEach` is worth the code clarity by 
removing the size check at the beginning, but up to you.
   
   `allInstances` is a one-liner in `ClusterInfo`:
   
   ```java
       public List<RingInstance> allInstances()
       {
           return new ArrayList<>(getTokenRangeReplicas().allInstances());
       }
   ```
   
   and in `ClusterInfoGroup`:
   
   ``` java
       public List<RingInstance> allInstances()
       {
           return applyOnEach(ci -> ci.allInstances())
                  .values().stream().flatMap(Collection::stream)
                  .collect(Collectors.toUnmodifiableList());
       }
   ```



##########
cassandra-analytics-core/src/main/java/org/apache/cassandra/spark/bulkwriter/coordinatedwrite/CassandraClusterInfoGroup.java:
##########
@@ -0,0 +1,300 @@
+/*
+ * 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.spark.bulkwriter.coordinatedwrite;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.EnumSet;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.function.Consumer;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+
+import com.google.common.base.Preconditions;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import o.a.c.sidecar.client.shaded.common.response.TimeSkewResponse;
+import org.apache.cassandra.bridge.CassandraVersionFeatures;
+import org.apache.cassandra.spark.bulkwriter.CassandraContext;
+import org.apache.cassandra.spark.bulkwriter.ClusterInfo;
+import org.apache.cassandra.spark.bulkwriter.WriteAvailability;
+import org.apache.cassandra.spark.bulkwriter.RingInstance;
+import org.apache.cassandra.spark.bulkwriter.token.TokenRangeMapping;
+import org.apache.cassandra.spark.data.ReplicationFactor;
+import org.apache.cassandra.spark.data.partitioner.Partitioner;
+import org.apache.cassandra.spark.utils.MapUtils;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+
+public class CassandraClusterInfoGroup implements ClusterInfo, 
MultiClusterInfoProvider

Review Comment:
   This class needs unit tests



##########
cassandra-analytics-core/src/main/java/org/apache/cassandra/spark/sparksql/CassandraDataSink.java:
##########
@@ -73,7 +71,7 @@ public BaseRelation createRelation(@NotNull SQLContext 
sqlContext,
             case Append:
                 // Initialize the job group ID for later use if we need to 
cancel the job
                 // TODO: Can we get a more descriptive "description" in here 
from the end user somehow?
-                BulkWriterContext writerContext = createBulkWriterContext(
+                BulkWriterContext writerContext = 
factory().createBulkWriterContext(

Review Comment:
   Realize it didn't happen in this PR, but the comments above this line has 
somehow never been kept with the code that they actually apply to - can you 
please move them back to the line where we actually call `setJobGroup` and 
remove the TODO at this point?



##########
cassandra-analytics-common/src/main/java/org/apache/cassandra/spark/utils/MapUtils.java:
##########
@@ -279,4 +282,19 @@ public static <T> T resolveDeprecated(Map<String, String> 
options, String option
 
         return deprecatedOptionValue == null ? resolver.apply(null) : 
deprecatedOptionValue;
     }
+
+    /**
+     * Get the first map entry from the map
+     *
+     * @return the first map entry, if there are at least one entry in the map
+     * @throws NoSuchElementException if the map is emtpy
+     */
+    public static <K, T> Map.Entry<K, T> firstEntry(@NotNull Map<K, T> map)

Review Comment:
   This is somewhat misleading, as _most_ maps have no concept of order. What 
exactly is it trying to achieve, and is "first" really what we mean here (in 
which case you probably want to have the parameter to be a `SortedMap`, but 
from the usage in CassandraClusterInfoGroup it seems to be more like 
`anyEntry`, but I think you can just remove this all together and just do 
something like I recommend in the usage below.
   
   Otherwise, I'd rename this `anyEntry`



-- 
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: commits-unsubscr...@cassandra.apache.org

For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscr...@cassandra.apache.org
For additional commands, e-mail: commits-h...@cassandra.apache.org

Reply via email to