clohfink commented on code in PR #3367:
URL: https://github.com/apache/cassandra/pull/3367#discussion_r1683351680


##########
src/java/org/apache/cassandra/repair/autorepair/AutoRepairUtils.java:
##########
@@ -0,0 +1,806 @@
+/*
+ * 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.repair.autorepair;
+
+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.TreeSet;
+import java.util.UUID;
+import java.util.concurrent.TimeUnit;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.MoreObjects;
+import com.google.common.collect.Lists;
+
+import org.apache.cassandra.locator.LocalStrategy;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.apache.cassandra.config.DatabaseDescriptor;
+import org.apache.cassandra.cql3.QueryOptions;
+import org.apache.cassandra.cql3.QueryProcessor;
+import org.apache.cassandra.cql3.UntypedResultSet;
+import org.apache.cassandra.cql3.statements.ModificationStatement;
+import org.apache.cassandra.cql3.statements.SelectStatement;
+import org.apache.cassandra.db.ConsistencyLevel;
+import org.apache.cassandra.db.Keyspace;
+import org.apache.cassandra.db.marshal.UTF8Type;
+import org.apache.cassandra.db.marshal.UUIDType;
+import org.apache.cassandra.gms.Gossiper;
+import org.apache.cassandra.locator.AbstractReplicationStrategy;
+import org.apache.cassandra.locator.InetAddressAndPort;
+import org.apache.cassandra.locator.NetworkTopologyStrategy;
+import org.apache.cassandra.schema.Schema;
+import org.apache.cassandra.schema.SchemaConstants;
+import org.apache.cassandra.schema.TableMetadata;
+import org.apache.cassandra.schema.ViewMetadata;
+import org.apache.cassandra.serializers.SetSerializer;
+import org.apache.cassandra.serializers.UUIDSerializer;
+import org.apache.cassandra.service.AutoRepairService;
+import org.apache.cassandra.service.ClientState;
+import org.apache.cassandra.service.QueryState;
+import org.apache.cassandra.service.StorageService;
+import org.apache.cassandra.transport.Dispatcher;
+import org.apache.cassandra.transport.ProtocolVersion;
+import org.apache.cassandra.transport.messages.ResultMessage;
+import org.apache.cassandra.utils.ByteBufferUtil;
+import org.apache.cassandra.utils.FBUtilities;
+import org.apache.cassandra.repair.autorepair.AutoRepairConfig.RepairType;
+
+import static 
org.apache.cassandra.repair.autorepair.AutoRepairUtils.RepairTurn.MY_TURN;
+import static 
org.apache.cassandra.repair.autorepair.AutoRepairUtils.RepairTurn.MY_TURN_DUE_TO_PRIORITY;
+import static 
org.apache.cassandra.repair.autorepair.AutoRepairUtils.RepairTurn.NOT_MY_TURN;
+import static 
org.apache.cassandra.repair.autorepair.AutoRepairUtils.RepairTurn.MY_TURN_FORCE_REPAIR;
+
+/**
+ * This class serves as a utility class for AutoRepair. It contains various 
helper APIs
+ * to store/retrieve repair status, decide whose turn is next, etc.
+ */
+public class AutoRepairUtils
+{
+    private static final Logger logger = 
LoggerFactory.getLogger(AutoRepairUtils.class);
+    static final String COL_REPAIR_TYPE = "repair_type";
+    static final String COL_HOST_ID = "host_id";
+    static final String COL_REPAIR_START_TS = "repair_start_ts";
+    static final String COL_REPAIR_FINISH_TS = "repair_finish_ts";
+    static final String COL_REPAIR_PRIORITY = "repair_priority";
+    static final String COL_DELETE_HOSTS = "delete_hosts";  // this set stores 
the host ids which think the row should be deleted
+    static final String COL_REPAIR_TURN = "repair_turn";  // this record the 
last repair turn. Normal turn or turn due to priority
+    static final String COL_DELETE_HOSTS_UPDATE_TIME = 
"delete_hosts_update_time"; // the time when delete hosts are upated
+    static final String COL_FORCE_REPAIR = "force_repair";  // if set to true, 
the node will do non-primary range rapair
+
+    final static String SELECT_REPAIR_HISTORY = String.format(
+    "SELECT * FROM %s.%s WHERE %s = ?", 
SchemaConstants.DISTRIBUTED_KEYSPACE_NAME,
+    AutoRepairKeyspace.AUTO_REPAIR_HISTORY, COL_REPAIR_TYPE);
+    final static String SELECT_REPAIR_PRIORITY = String.format(
+    "SELECT * FROM %s.%s WHERE %s = ?", 
SchemaConstants.DISTRIBUTED_KEYSPACE_NAME,
+    AutoRepairKeyspace.AUTO_REPAIR_PRIORITY, COL_REPAIR_TYPE);
+    final static String DEL_REPAIR_PRIORITY = String.format(
+    "DELETE %s[?] FROM %s.%s WHERE %s = ?", COL_REPAIR_PRIORITY, 
SchemaConstants.DISTRIBUTED_KEYSPACE_NAME,
+    AutoRepairKeyspace.AUTO_REPAIR_PRIORITY, COL_REPAIR_TYPE);
+    final static String ADD_PRIORITY_HOST = String.format(
+    "UPDATE %s.%s SET %s = %s + ?  WHERE %s = ?", 
SchemaConstants.DISTRIBUTED_KEYSPACE_NAME,
+    AutoRepairKeyspace.AUTO_REPAIR_PRIORITY, COL_REPAIR_PRIORITY, 
COL_REPAIR_PRIORITY, COL_REPAIR_TYPE);
+
+    final static String INSERT_NEW_REPAIR_HISTORY = String.format(
+    "INSERT INTO %s.%s (%s, %s, %s, %s, %s, %s) values (?, ? ,?, ?, {}, ?) IF 
NOT EXISTS",
+    SchemaConstants.DISTRIBUTED_KEYSPACE_NAME, 
AutoRepairKeyspace.AUTO_REPAIR_HISTORY, COL_REPAIR_TYPE,
+    COL_HOST_ID, COL_REPAIR_START_TS, COL_REPAIR_FINISH_TS, COL_DELETE_HOSTS, 
COL_DELETE_HOSTS_UPDATE_TIME);
+
+    final static String ADD_HOST_ID_TO_DELETE_HOSTS = String.format(
+    "UPDATE %s.%s SET %s = %s + ?, %s = ? WHERE %s = ? AND %s = ? IF EXISTS"
+    , SchemaConstants.DISTRIBUTED_KEYSPACE_NAME, 
AutoRepairKeyspace.AUTO_REPAIR_HISTORY, COL_DELETE_HOSTS,
+    COL_DELETE_HOSTS, COL_DELETE_HOSTS_UPDATE_TIME, COL_REPAIR_TYPE, 
COL_HOST_ID);
+
+    final static String DEL_AUTO_REPAIR_HISTORY = String.format(
+    "DELETE FROM %s.%s WHERE %s = ? AND %s = ?"
+    , SchemaConstants.DISTRIBUTED_KEYSPACE_NAME, 
AutoRepairKeyspace.AUTO_REPAIR_HISTORY, COL_REPAIR_TYPE,
+    COL_HOST_ID);
+
+    final static String RECORD_START_REPAIR_HISTORY = String.format(
+    "UPDATE %s.%s SET %s= ?, repair_turn = ? WHERE %s = ? AND %s = ?"
+    , SchemaConstants.DISTRIBUTED_KEYSPACE_NAME, 
AutoRepairKeyspace.AUTO_REPAIR_HISTORY, COL_REPAIR_START_TS,
+    COL_REPAIR_TYPE, COL_HOST_ID);
+
+    final static String RECORD_FINISH_REPAIR_HISTORY = String.format(
+
+    "UPDATE %s.%s SET %s= ?, %s=false WHERE %s = ? AND %s = ?"
+    , SchemaConstants.DISTRIBUTED_KEYSPACE_NAME, 
AutoRepairKeyspace.AUTO_REPAIR_HISTORY, COL_REPAIR_FINISH_TS,
+    COL_FORCE_REPAIR, COL_REPAIR_TYPE, COL_HOST_ID);
+
+    final static String CLEAR_DELETE_HOSTS = String.format(
+    "UPDATE %s.%s SET %s= {} WHERE %s = ? AND %s = ?"
+    , SchemaConstants.DISTRIBUTED_KEYSPACE_NAME, 
AutoRepairKeyspace.AUTO_REPAIR_HISTORY, COL_DELETE_HOSTS,
+    COL_REPAIR_TYPE, COL_HOST_ID);
+
+    final static String SET_FORCE_REPAIR = String.format(
+    "UPDATE %s.%s SET %s=true  WHERE %s = ? AND %s = ?"
+    , SchemaConstants.DISTRIBUTED_KEYSPACE_NAME, 
AutoRepairKeyspace.AUTO_REPAIR_HISTORY, COL_FORCE_REPAIR,
+    COL_REPAIR_TYPE, COL_HOST_ID);
+
+    static ModificationStatement delStatementRepairHistory;
+    static SelectStatement selectStatementRepairHistory;
+    static ModificationStatement delStatementPriorityStatus;
+    static SelectStatement selectStatementRepairPriority;
+    static ModificationStatement addPriorityHost;
+    static ModificationStatement insertNewRepairHistoryStatement;
+    static ModificationStatement recordStartRepairHistoryStatement;
+    static ModificationStatement recordFinishRepairHistoryStatement;
+    static ModificationStatement addHostIDToDeleteHostsStatement;
+    static ModificationStatement clearDeleteHostsStatement;
+    static ModificationStatement setForceRepairStatement;
+    static ConsistencyLevel internalQueryCL;
+
+    public enum RepairTurn
+    {
+        MY_TURN,
+        NOT_MY_TURN,
+        MY_TURN_DUE_TO_PRIORITY,
+        MY_TURN_FORCE_REPAIR
+    }
+
+    public static void setup()
+    {
+        selectStatementRepairHistory = (SelectStatement) 
QueryProcessor.getStatement(SELECT_REPAIR_HISTORY, ClientState
+                                                                               
                             .forInternalCalls());
+        selectStatementRepairPriority = (SelectStatement) 
QueryProcessor.getStatement(SELECT_REPAIR_PRIORITY, ClientState
+                                                                               
                               .forInternalCalls());
+        delStatementPriorityStatus = (ModificationStatement) 
QueryProcessor.getStatement(DEL_REPAIR_PRIORITY, ClientState
+                                                                               
                               .forInternalCalls());
+        addPriorityHost = (ModificationStatement) 
QueryProcessor.getStatement(ADD_PRIORITY_HOST, ClientState
+                                                                               
                  .forInternalCalls());
+        insertNewRepairHistoryStatement = (ModificationStatement) 
QueryProcessor.getStatement(INSERT_NEW_REPAIR_HISTORY, ClientState
+                                                                               
                                          .forInternalCalls());
+        recordStartRepairHistoryStatement = (ModificationStatement) 
QueryProcessor.getStatement(RECORD_START_REPAIR_HISTORY, ClientState
+                                                                               
                                              .forInternalCalls());
+        recordFinishRepairHistoryStatement = (ModificationStatement) 
QueryProcessor.getStatement(RECORD_FINISH_REPAIR_HISTORY, ClientState
+                                                                               
                                                .forInternalCalls());
+        addHostIDToDeleteHostsStatement = (ModificationStatement) 
QueryProcessor.getStatement(ADD_HOST_ID_TO_DELETE_HOSTS, ClientState
+                                                                               
                                            .forInternalCalls());
+        setForceRepairStatement = (ModificationStatement) 
QueryProcessor.getStatement(SET_FORCE_REPAIR, ClientState
+                                                                               
                         .forInternalCalls());
+        clearDeleteHostsStatement = (ModificationStatement) 
QueryProcessor.getStatement(CLEAR_DELETE_HOSTS, ClientState
+                                                                               
                             .forInternalCalls());
+        delStatementRepairHistory = (ModificationStatement) 
QueryProcessor.getStatement(DEL_AUTO_REPAIR_HISTORY, ClientState
+                                                                               
                                  .forInternalCalls());
+        Keyspace autoRepairKS = 
Schema.instance.getKeyspaceInstance(SchemaConstants.DISTRIBUTED_KEYSPACE_NAME);
+        internalQueryCL = autoRepairKS.getReplicationStrategy().getClass() == 
NetworkTopologyStrategy.class ?
+                          ConsistencyLevel.LOCAL_QUORUM : ConsistencyLevel.ONE;
+    }
+
+    public static class AutoRepairHistory
+    {
+        UUID hostId;
+        String repairTurn;
+        long lastRepairStartTime;
+        long lastRepairFinishTime;
+        Set<UUID> deleteHosts;
+        long deleteHostsUpdateTime;
+        boolean forceRepair;
+
+        public AutoRepairHistory(UUID hostId, String repairTurn, long 
lastRepairStartTime, long lastRepairFinishTime,
+                                 Set<UUID> deleteHosts, long 
deleteHostsUpateTime, boolean forceRepair)
+        {
+            this.hostId = hostId;
+            this.repairTurn = repairTurn;
+            this.lastRepairStartTime = lastRepairStartTime;
+            this.lastRepairFinishTime = lastRepairFinishTime;
+            this.deleteHosts = deleteHosts;
+            if (this.deleteHosts == null)
+            {
+                this.deleteHosts = new HashSet<>();
+            }
+            this.deleteHostsUpdateTime = deleteHostsUpateTime;
+            this.forceRepair = forceRepair;
+        }
+
+        public String toString()
+        {
+            return MoreObjects.toStringHelper(this).
+                              add("hostId", hostId).
+                              add("repairTurn", repairTurn).
+                              add("lastRepairStartTime", lastRepairStartTime).
+                              add("lastRepairFinishTime", 
lastRepairFinishTime).
+                              add("deleteHosts", deleteHosts).
+                              toString();
+        }
+
+        public boolean isRepairRunning()
+        {
+            // if a repair history record has start time laster than finish 
time, it means the repair is running
+            return lastRepairStartTime > lastRepairFinishTime;
+        }
+
+        public long getLastRepairFinishTime()
+        {
+            return lastRepairFinishTime;
+        }
+    }
+
+    public static class CurrentRepairStatus
+    {
+        public Set<UUID> hostIdsWithOnGoingRepair;  // hosts that is running 
repair
+        public Set<UUID> hostIdsWithOnGoingForceRepair; // hosts that is 
running repair because of force repair
+        Set<UUID> priority;
+        List<AutoRepairHistory> historiesWithoutOnGoingRepair;  // hosts that 
is NOT running repair
+
+        public CurrentRepairStatus(List<AutoRepairHistory> repairHistories, 
Set<UUID> priority)
+        {
+            hostIdsWithOnGoingRepair = new HashSet<>();
+            hostIdsWithOnGoingForceRepair = new HashSet<>();
+            historiesWithoutOnGoingRepair = new ArrayList<>();
+
+            for (AutoRepairHistory history : repairHistories)
+            {
+                if (history.isRepairRunning())
+                {
+                    if (history.forceRepair)
+                    {
+                        hostIdsWithOnGoingForceRepair.add(history.hostId);
+                    }
+                    else
+                    {
+                        hostIdsWithOnGoingRepair.add(history.hostId);
+                    }
+                }
+                else
+                {
+                    historiesWithoutOnGoingRepair.add(history);
+                }
+            }
+            this.priority = priority;
+        }
+
+        public String toString()
+        {
+            return MoreObjects.toStringHelper(this).
+                              add("hostIdsWithOnGoingRepair", 
hostIdsWithOnGoingRepair).
+                              add("hostIdsWithOnGoingForceRepair", 
hostIdsWithOnGoingForceRepair).
+                              add("historiesWithoutOnGoingRepair", 
historiesWithoutOnGoingRepair).
+                              add("priority", priority).
+                              toString();
+        }
+    }
+
+    @VisibleForTesting
+    public static List<AutoRepairHistory> 
getAutoRepairHistoryByGroupID(RepairType repairType)
+    {
+        UntypedResultSet repairHistoryResult;
+
+        ResultMessage.Rows repairStatusRows = 
selectStatementRepairHistory.execute(QueryState.forInternalCalls(),
+                                                                               
    QueryOptions.forInternalCalls(internalQueryCL, 
Lists.newArrayList(ByteBufferUtil.bytes(repairType.toString()))), 
Dispatcher.RequestTime.forImmediateExecution());
+        repairHistoryResult = UntypedResultSet.create(repairStatusRows.result);
+
+        List<AutoRepairHistory> repairHistories = new ArrayList<>();
+        if (repairHistoryResult.size() > 0)
+        {
+            for (UntypedResultSet.Row row : repairHistoryResult)
+            {
+                UUID hostId = row.getUUID(COL_HOST_ID);
+                String repairTurn = null;
+                if (row.has(COL_REPAIR_TURN))
+                    repairTurn = row.getString(COL_REPAIR_TURN);
+                long lastRepairStartTime = row.getLong(COL_REPAIR_START_TS, 0);
+                long lastRepairFinishTime = row.getLong(COL_REPAIR_FINISH_TS, 
0);
+                Set<UUID> deleteHosts = row.getSet(COL_DELETE_HOSTS, 
UUIDType.instance);
+                long deleteHostsUpdateTime = 
row.getLong(COL_DELETE_HOSTS_UPDATE_TIME, 0);
+                Boolean forceRepair = row.has(COL_FORCE_REPAIR) ? 
row.getBoolean(COL_FORCE_REPAIR) : false;
+                repairHistories.add(new AutoRepairHistory(hostId, repairTurn, 
lastRepairStartTime, lastRepairFinishTime,
+                                                          deleteHosts, 
deleteHostsUpdateTime, forceRepair));
+            }
+            return repairHistories;
+        }
+        logger.info("No repair history found");
+        return null;
+    }
+
+    public static List<AutoRepairHistory> 
getAutoRepairHistoryForLocalGroup(RepairType repairType)
+    {
+        return getAutoRepairHistoryByGroupID(repairType);
+    }
+
+    // A host may add itself in delete hosts for some other hosts due to 
restart or some temp gossip issue. If a node's record
+    // delete_hosts is not growing for more than 2 hours, we consider it as a 
normal node so we clear the delete_hosts for that node
+    public static void clearDeleteHosts(RepairType repairType, UUID hostId)
+    {
+        clearDeleteHostsStatement.execute(QueryState.forInternalCalls(),
+                                          
QueryOptions.forInternalCalls(internalQueryCL,
+                                                                        
Lists.newArrayList(ByteBufferUtil.bytes(repairType.toString()),
+                                                                               
            ByteBufferUtil.bytes(hostId))), 
Dispatcher.RequestTime.forImmediateExecution());
+    }
+
+    public static void setForceRepairNewNode(RepairType repairType)
+    {
+        // this function will be called when a node bootstrap finished
+        UUID hostId = 
Gossiper.instance.getHostId(FBUtilities.getBroadcastAddressAndPort());
+        // insert the data first
+        insertNewRepairHistory(repairType, System.currentTimeMillis(), 
System.currentTimeMillis());

Review Comment:
   fails checkstyles,  use org.apache.cassandra.utils.Clock.Global or 
org.apache.cassandra.utils.Clock interface



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

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