minal-kyada commented on code in PR #4630:
URL: https://github.com/apache/cassandra/pull/4630#discussion_r2898091524


##########
src/java/org/apache/cassandra/db/SystemPeersValidator.java:
##########
@@ -0,0 +1,227 @@
+/*
+ * 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.db;
+
+import java.net.InetAddress;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.apache.cassandra.cql3.UntypedResultSet;
+import org.apache.cassandra.db.marshal.UTF8Type;
+import org.apache.cassandra.db.virtual.PeersTable;
+import org.apache.cassandra.locator.InetAddressAndPort;
+import org.apache.cassandra.schema.SchemaConstants;
+import org.apache.cassandra.tcm.ClusterMetadata;
+import org.apache.cassandra.tcm.membership.Location;
+import org.apache.cassandra.tcm.membership.NodeAddresses;
+import org.apache.cassandra.tcm.membership.NodeId;
+import org.apache.cassandra.utils.FBUtilities;
+
+import static org.apache.cassandra.cql3.QueryProcessor.executeInternal;
+import static org.apache.cassandra.db.SystemKeyspace.LEGACY_PEERS;
+import static org.apache.cassandra.db.SystemKeyspace.PEERS_V2;
+
+/**
+ * Validator to ensure system.peers and system.peers_v2 tables match 
ClusterMetadata on startup.
+ * This is critical for backward compatibility as older clients and tools read 
from these
+ * legacy tables while TCM uses ClusterMetadata as the source of truth.
+ *
+ * The validator detects inconsistencies and automatically repairs them by 
synchronizing
+ * the peers tables with the current ClusterMetadata.
+ */
+public class SystemPeersValidator
+{
+    private static final Logger logger = 
LoggerFactory.getLogger(SystemPeersValidator.class);
+
+    public static void validateAndRepair(ClusterMetadata metadata)
+    {
+        Map<InetAddressAndPort, UntypedResultSet.Row> peersV2Rows = 
getPeersV2Rows();
+        Map<InetAddress, UntypedResultSet.Row> legacyPeersRows = 
getLegacyPeersRows();
+
+        Map<InetAddressAndPort, NodeId> expectedEndpoints = new HashMap<>();
+        Map<InetAddress, NodeId> expectedAddresses = new HashMap<>();
+        for (NodeId nodeId : getExpectedPeerNodes(metadata))
+        {
+            InetAddressAndPort endpoint = metadata.directory.endpoint(nodeId);
+            expectedEndpoints.put(endpoint, nodeId);
+            expectedAddresses.put(endpoint.getAddress(), nodeId);
+        }
+
+        String deleteV2Query = String.format("DELETE FROM %s.%s WHERE peer = ? 
AND peer_port = ?",
+                                               
SchemaConstants.SYSTEM_KEYSPACE_NAME, PEERS_V2);
+        for (InetAddressAndPort endpoint : peersV2Rows.keySet())
+        {
+            if (!expectedEndpoints.containsKey(endpoint))
+            {
+                logger.info("Removing stale peer {} from {}", endpoint, 
PEERS_V2);
+                executeInternal(deleteV2Query, endpoint.getAddress(), 
endpoint.getPort());
+            }
+        }
+
+        String deleteLegacyQuery = String.format("DELETE FROM %s.%s WHERE peer 
= ?",
+                                                   
SchemaConstants.SYSTEM_KEYSPACE_NAME,
+                                                   LEGACY_PEERS);
+        for (InetAddress address : legacyPeersRows.keySet())
+        {
+            if (!expectedAddresses.containsKey(address))
+            {
+                logger.info("Removing stale peer {} from {}", address, 
LEGACY_PEERS);
+                executeInternal(deleteLegacyQuery, address);
+            }
+        }
+
+        for (Map.Entry<InetAddressAndPort, NodeId> entry : 
expectedEndpoints.entrySet())
+        {
+            NodeId nodeId = entry.getValue();
+            InetAddressAndPort endpoint = entry.getKey();
+            UntypedResultSet.Row v2Row = peersV2Rows.get(endpoint);
+            UntypedResultSet.Row legacyRow = 
legacyPeersRows.get(endpoint.getAddress());
+
+            List<String> v2Discrepancies = collectV2Discrepancies(v2Row, 
nodeId, metadata);

Review Comment:
   > null safety
    
   Thanks for sharing this, I should definitely add it, as except for 
`getSet()`, none of the getters have null guards. I'll add `has()` checks 
before each getter and treat a missing column as a discrepancy.    
   
   > consolidating the two methods
   
   I did consider it, but reverted that change because I found it more 
convenient to see the complete set of validations for a given table at a glance 
without jumping between methods. A shared helper would still need 
table-specific checks alongside it, so I'd end up fragmenting the logic across 
multiple methods for what is a fairly simple use case. That said, happy to 
revisit if you feel strongly about it.
   
   > per-field discrepancy logging
   
   It tells an operator exactly what's wrong — e.g. `Updating peer 10.0.0.1 in 
peers_v2 for stale fields [data_center, rack]`. With Row::toString(), we will 
get pipe-delimited positional values without column names, and the operator 
would have to figure out the diff manually to identify what's stale. For 
something meant to be a diagnostic/repair tool, don't you think having the 
specific out-of-sync fields is more helpful? I also checked the rest of the 
codebase and we always extract fields and log them by name. Please let me know 
if it is useful to know this information from operator POV, else we can 
definitely add this change ?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

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


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

Reply via email to